15

I'm trying to redirect from one page to another while retaining the parameters.

e.g. if I have a page page.php?param1=1&param2=2, what's the easiest way to extract "param1=1&param2=2"?

4 Answers 4

43

Use $_SERVER['QUERY_STRING'] to access everything after the question mark.

So if you have the url:

http://www.sample.com/page.php?param1=1&param2=2

then this:

$url = "http://www.sample.com/page2.php?".$_SERVER['QUERY_STRING'];
echo $url;

will return:

http://www.sample.com/page2.php?param1=1&param2=2
Sign up to request clarification or add additional context in comments.

Comments

9

In addition to Robs answer:

You can use http_build_query and $_GET.
This is build-in and can deal with arrays.
Also you can easily manipulate the GET params this way, befor you put them together again.

unset($_GET['unsetthis']);
$query = http_build_query($_GET);

Comments

7

$_SERVER['QUERY_STRING']

Source

Comments

5

i would do

$querystring = '?'
foreach($_GET as $k=>$v) {
    $querystring .= $k.'='.$v.'&';
}
$url .= substr($querystring, 0, -1);

where $url already contains everything before the ?

you could also use $_SERVER['QUERY_STRING'] but as per the PHP manual:

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. *There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. *

2 Comments

That's technically true, but whatever web server he's using almost certainly provides $_SERVER['QUERY_STRING']; most PHP-based systems rely on it existing
this will also not render arrays like: key[innerkey]=value . it will get you: key=Array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.