简体   繁体   中英

How to get visible query string and not parsed query string by rules or htaccess in PHP

I have a url that parts of it are converted into variables through htaccess and other parts are variables sent in GET.

mydomain.com/page/5/string?v2=foo&v3=bar

.httaccess sends 5 as a variable, let's call it v1

RewriteRule ^([^/]*)/([0-9]+)/(.*)$ page.php?v1=$2 [L,QSA]

And the rest of the query string are received as GET.

?v2=foo&v3=bar

In this example, it is very straight forward, but in the actual system the variables parsed by .htaccess are more than one and are dynamic,

I need to find a way to only get the variables sent in GET ignoring the ones from .htaccess.

I tried $_SERVER['QUERY_STRING'] but that one returns also the variables parsed by .htaccess:

echo $_SERVER['QUERY_STRING'] //returns v1=5&v2=foo&v3=bar

I only want to get v2=foo&v3=bar

I think you can read $_SERVER['REQUEST_URI'] and use proper regex to take the GET variables from URL. And then (if you need) you could write function to split them to array of variables:

$get = array(); //array for GET values
$uri = $_SERVER['REQUEST_URI'];

$uri_parts = explode('?', $uri, 2);
$get_string = $uri_parts[1]; //[0] is address

$get_pairs = explode('&', $get_string); //split to key=value pairs
foreach($get_pairs as $get_pair){
  list($key, $value) = explode('=', $get_pair, 2); //split key and value
  $get[$key] = $value;
}

$get_string contains string like a=bc&d=ef

$get contains key-value pairs (like $_GET )

I need to find a way to only get the variables sent in GET ignoring the ones from .htaccess.

You can use an environment variable to pass original query string to your php file:

RewriteRule ^([^/]+)/([0-9]+)/(.*)$ page.php?v1=$2 [E=qs:%{QUERY_STRING},L,QSA]

Now access original query string using this variable in php code:

$_SERVER["REDIRECT_qs"]

This should print:

v2=foo&v3=bar

Whereas $_SERVER["QUERY_STRING"] will give you full query string ie v1=5&v2=foo&v3=bar

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