Php add / change query string parameter and get url

How to redirect the user back to the same page with existing Query Strings, but you have 1 added / changed as a "page".

I assume 1 method:

  • parse $_SERVER['QUERY_STRING'] into an array
  • if page exists in the array, change the value, otherwise add it
  • use http_build_query to add a query string to $_SERVER['PHP_SELF']

but is there a better / more direct way?

+7
source share
2 answers

To make sure you know about this, use parse_str to parse the query string:

 <?php parse_str($_SERVER['QUERY_STRING'], $query_string); $query_string['page'] = basename($_SERVER['PHP_SELF']); $rdr_str = http_build_query($query_string); 
+21
source

Using Jim Rubinstein's answer, I came up with a useful feature that I thought I could share:

  function modQuery($add_to, $rem_from = array(), $clear_all = false){ if ($clear_all){ $query_string = array(); }else{ parse_str($_SERVER['QUERY_STRING'], $query_string); } if (!is_array($add_to)){ $add_to = array(); } $query_string = array_merge($query_string, $add_to); if (!is_array($rem_from)){ $rem_from = array($rem_from); } foreach($rem_from as $key){ unset($query_string[$key]); } return http_build_query($query_string); } 

For example: <a href="?<?=modQuery(array('kind'=>'feature'))?>">Feature</a>

+4
source

All Articles