Persistent HTTP GET variables in PHP

Say I have code like this

if(isset($_GET['foo'])) //do something if(isset($_GET['bar'])) //do something else 

If the user is located in example.com/?foo=abc and clicks on the link to set bar = xyz, I just want to take them to example.com/?foo=abc&bar=xyz, not the example .com /? bar = hug.

I can come up with some very dirty ways to do this, but I'm sure there is something cleaner there that I don’t know about and could not track through Google.

+4
source share
5 answers

Here is one way ....

 //get passed params //(you might do some sanitizing at this point) $params=$_GET; //morph the params with new values $params['bar']='xyz'; //build new query string $query=''; $sep='?'; foreach($params as $name=>$value) { $query.=$sep.$name.'='.urlencode($value); $sep='&'; } 
+2
source

If you update the query string, you need you to not do something like

 $qs="a=1&b=2"; $href="$qs&b=4"; $href contains "a=1&b=2&b=4" 

What you really want to do is overwrite the current key if you need to. You can use such a function. (disclaimer: from head to head, maybe a little bugged)

  function getUpdateQS($key,$value) { foreach ($_GET as $k => $v) { if ($k != $key) { $qs .= "$k=".urlencode($v)."&" } else { $qs .= "$key=".urlencode($value)."&"; } } return $qs } <a href="reports.php?<?getupdateqs('name','byron');?">View report</a> 
+1
source

Just set the link that will change the line to xyz to have foo = abc if foo is already installed.

 $link = ($_GET['foo'] == 'abc') ? 'foo=abc&bar=xyz' : 'bar=xyz'; ?> <a href="whatever.php?<?= $link ?>">Click Me</a> 
0
source

You will need to display the links using the correct URL scrolling for this to happen. This is a design decision that you will need to make at the end, depending on the configuration of your system.

I have several sites that have this problem, and what I am doing is setting up a global query variable that sets the current page data at the top of the page request.

Then, when I draw the page, if I need to use the current query string, I do something like:

 echo '<a href="myurl.php' . querystring . '&bar=foo'; 

This is not the cleanest, but it all depends on how your system works.

0
source

Save the code and use the built-in http_build_query . I use this shell in one of my projects:

 function to_query_string($array) { if(is_scalar($array)) $query = trim($array, '? \t\n\r\0\x0B'); // I could split on "&" and "=" do some urlencode-ing here else $query = http_build_query($array); return '?'.$query; } 

In addition, although it is not often used, you can have $ _GET on the left side of the assignment:

 $_GET['overriden_or_new'] = 'new_value'; echo '<a href="'.to_query_string($_GET).'">Yeah!</a>'; 

Other than that, just do what Paul Dixon said.

0
source

All Articles