Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping URL parameters during PHP redirect

Tags:

html

php

This isn't working:

<?php
header('Location: www.mysite.com/index.php?foo=bar&var=abc');
?>

I end up with www.mysite.com/index.php?foo=bar I think HTML might be trying to interpret the &var as a character. The initial variable is passed (after ?) but all subsequent are not (after &).

like image 483
joedborg Avatar asked Sep 09 '11 10:09

joedborg


People also ask

How to redirect a URL in PHP?

Most guides will tell you that to make a PHP redirect you can just use the header () function at the top of your pages. To do that, you use the function to send a new URL, like this: This header function should be put before you pass any HTML or text to your users’ browsers, so it should be right at the top of the page.

How to do a 301 redirect with parameters to another page?

To do a 301 PHP redirect with parameters to another page we can use the following code: <?php $url = "landingPage2.php?".$_SERVER ['QUERY_STRING']; header ("HTTP/1.1 301 Moved Permanently"); header ("Location: $url"); ?> The entire query parameter string is stored in the following variable. Everything after the question mark.

How to get parameters from a URL string in PHP?

Almost all developers at least once in their practice have wondered how to get parameters from a URL string with the help of PHP functions. In our tutorial, we will provide you with two simple and handy functions such as pase_url () and parse_str () that will allow you to do that. Read on and check out the options below.

How to protect the rest of the page when redirecting?

If, in other words, you are using a header redirect to protect a particular page, it offers you no protection at all. That’s why you have to stop processing the rest of the page, in case the redirection is ignored. The way to do that is to append die () or exit () after your redirect: Next, let’s talk about relative and absolute URLs in redirects.


1 Answers

if( isset($_SERVER['HTTPS'] ) ) {
  header('Location: https://'.$_SERVER['SERVER_NAME'].'/index.php?'.$_SERVER['QUERY_STRING']);
}
else{
  header('Location: http://'.$_SERVER['SERVER_NAME'].'/index.php?'.$_SERVER['QUERY_STRING']);
} 

use htmlspecialchars to prevent html injection

like image 122
confucius Avatar answered Oct 08 '22 21:10

confucius