php redirect with HTTP query string variables
atm I'm using the following four lines to redirect the user to another page on my website:
<?php
header("Status: 301 Moved Permanently");
header("Location: ./content/index.html");
exit;
?>
but there is a problem with the use of HTTP query string variables like http://< url >?param=blah
they don't get appended to url understandably.
Is there a smart move for implementing this?
greetings
Solution 1:
<?php
header("Status: 301 Moved Permanently");
header("Location:./content/index.html?". $_SERVER['QUERY_STRING']);
exit;
?>
Solution 2:
To do the redirect and make sure an extra question mark does not show up when query string is not passed use the following
function preserve_qs() {
if (empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['REQUEST_URI'], "?") === false) {
return "";
}
return "?" . $_SERVER['QUERY_STRING'];
}
header("Status: 301 Moved Permanently");
header("Location: ./content/index.html" . preserve_qs());
Solution 3:
I would like to add one more option...
Anyways - like others have said, using (.htaccess) mod_rewrite would probably be the best option.
However,
there surely can be many situations when you have to do it in PHP => you have 2 options:
- Append your redirection URI with
$_SERVER['QUERY_STRING']
- Append your redirection URI with a query built on your own :
http_build_query($_GET);
Option 2. - Advantages (+)
- Encodes the parameters ( default by PHP_QUERY_RFC1738 )
- you can easily add (or remove) some
$_GET
params like:$_GET['new_param']="new value";
(add)unset($_GET['param_to_remove']);
(remove) - if environment (god knows why) does not provide a QUERY_STRING - you are probably still able to get the superglobal
$_GET
=> environmentaly independent -
http_build_query()
's 1st param can actually be ANY array or object so you can build a$_GET
-like request from$_POST
or$o = new YourObject();
if necessary - you can change argument separator if necessary
Option 2. - Dissadvantages (-)
- this kind of building query might be redundant ("good-for-nothing"), just unnecessary...
- if the query is big enaugh (maybe some attack?) it could have an affect on performace, because everytime there will be an array converted to a string & encoded
For more info see http://www.php.net/manual/en/function.http-build-query.php - a PHP manual's site about the http_build_query()
function which Returns a URL-encoded string.