简体   繁体   中英

PHP - easiest way to get $_GET parameters string as written in the URL

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

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

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

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);

$_SERVER['QUERY_STRING']

资源

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. *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM