Update March 2023
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.
$_SERVER['QUERY_STRING']
So for the URL: server.com/index.php?test=123&hi=hello
the $_SERVER[‘QUERY_STRING’] will contain this string “test=123&hi=hello”
We can then pass this out when redirecting landing page (see code below from original blog post).
If you want to access a single variable then you can use
$_GET['variableName'];
From the example URL above $_GET[‘hi’] === “hello”
So we could do something like the following to pass that parameter on
<?php
$url = "https://example.com/page.php?newvar=".$_GET['hi'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: $url");
?>
XSS
Cross site scripting is a security vulnerability that can be exploited by injecting malicious code into these variables.
To prevent this and if we know the variable will only contain alphanumeric characters we can sanitize the user defined input with this PHP code
$clean = preg_replace("/[^a-zA-Z0-9 ]/","",$_GET['variableName']);
Get variables should always be treated as malicious and should not be directly used in database queries without prior sanitizing.
Original Post | PHP Redirect with Parameters
This was something quite simple that shouldn’t have taken me as long as it did to figure out.
I had traffic going to one url: http://myserver.com/lander.php?source=google&campaign=no1&c1=foobar
I wanted to split the traffic to try two different conversion funnels. The thing was I needed to keep the source, campaign, c1 variables in the url and pass them through to the following landing page so they could be tracked correctly.
So I setup the two conversion funnels at:
lpa.php and lpb.php using the original as a template
Then I used the following code in lander.php to redirect the traffic to the new landing pages on a 50/50 split.
<?php
if (rand(0,1) == 0) {
$url = 'lpa.php';
} else {
$url = 'lpb.php';
}
header("Location: $url".'?'.$_SERVER['QUERY_STRING']);
?>
This is useful if you don’t want to change the URL at the traffic source and just split the traffic internally without messing up your logging.
The url paramaters that would normally be tracked with $_GET are passed via the $_SERVER[‘QUERY_STRING’] variable.