Suppose I want to redirect all GET
queries from one site to another, using PHP
.POST
queries do not exist in the system.
For example, when the user connects to
www.mysite.com/index.php?action=myAction&pageno=2
I want him to be redirected to:
www.mySecondSite.com/index.php?action=myAction&pageno=2
I can get write a hard-coded code for each and every possible $_GET
variable (myAction
and pageno
in my example), but it does not sound like a reasonable solution. Also, I've seen this solution which involves modifying the configuration of the Apache server. Suppose I can't change the server configuration.
For sure, there must be a way to get all of the variables and their values, and redirect it to another site.
First of all you need to get complete URL, for example for my local server:
http://localhost/server_var.php?foo=bar&second=something
Try printing $_SERVER
variable with print_r()
:
print_r( $_SERVER);
You should get result like this:
Array
(
...
[REQUEST_URI] => /server_var.php?foo=bar&second=something
...
)
For more info take a look at manual page, so now you have your URL:
$url = 'http://www.mySecondSite.com' . $_SERVER['REQUEST_URI'];
And you can use header()
to redirect your request:
header( 'Location: ' . $url);
I recommend taking look at HTTP status codes, 3xx
ones, whether you want to use 302 Found
(the default) or 307 Temporary Redirect
...
The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.
So you can do this:
header('HTTP/1.0 307 Temporary Redirect');
header( 'Location: ' . $url);
Write this php code at the top of the index.php page before your html tag.
<?
$newUrl = "www.mySecondSite.com/index.php";
if (!empty($_GET)){
$parameter = $_GET;
$firstTime = true;
foreach($parameter as $param => $value){
if ($firstTime) {
$newUrl .= "?" . $param . "=" . $value;
$firstTime = false;
} else {
$newUrl .= "&" . $param . "=" . $value;
}
}
}
header("Location: ".$newUrl);
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With