Reputation: 2812
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
Upvotes: 53
Views: 104724
Reputation: 10636
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());
Upvotes: 18
Reputation: 15052
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:
$_SERVER['QUERY_STRING']
http_build_query($_GET);
Option 2. - Advantages (+)
$_GET
params like:$_GET['new_param']="new value";
(add)unset($_GET['param_to_remove']);
(remove)$_GET
=> environmentaly independenthttp_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 necessaryOption 2. - Dissadvantages (-)
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.
Upvotes: 10
Reputation: 6554
<?php
header("Status: 301 Moved Permanently");
header("Location:./content/index.html?". $_SERVER['QUERY_STRING']);
exit;
?>
Upvotes: 106
Reputation: 450
I would also suggest to use mod_rewrite for this task, you can be more flexible.
Upvotes: 1
Reputation: 32537
First off why not redirect with mod rewrite?
But anyways, you can concat $_SERVER['QUERY_STRING'] to the end of your url
Upvotes: 2
Reputation: 159
Using $_SERVER['QUERY_STRING']
and appending it to the end of your redirect might be what you're looking for.
EDIT: Just noticed I was a bit late with my reply.
Upvotes: 4
Reputation: 9078
Add the $_SERVER['REQUEST_URI']
or QUERY_STRING
. Do a print_r($_SERVER);
to see more information about the requested URL.
Upvotes: 1