1

I'd like to create a link that changes a PHP $_GET variable. For example:

URL: http://site.com/index&variable=hello&anothervariable=dontchangeme

<a href="variable=world">Click me</a>

(after click)

URL: http://site.com/index&variable=world&anothervariable=dontchangeme

I know you can do this to just change the page (href="1.html"), but I'd like to do the same thing while maintaining the GET variables that were already there.

tkbx
  • 15,602
  • 32
  • 87
  • 122

4 Answers4

7
$query = array('variable' => 'world') + $_GET;

printf('<a href="index?%s">Click me</a>', http_build_query($query));

See http://php.net/http_build_query. That's the easy to understand minimal version. Correctly you need to also HTML-escape the generated query string (because you're putting it into HTML):

printf('<a href="index?%s">Click me</a>', htmlspecialchars(http_build_query($query)));
deceze
  • 510,633
  • 85
  • 743
  • 889
  • That seems interesting, it would nice if you explain the above code :) – Mr. Alien Dec 17 '12 at 16:02
  • If you read the documentation and play around with this a bit, it's pretty self-explanatory. You merge the existing `$_GET` array and your new value(s), then build a query string from them and put them in a link. – deceze Dec 17 '12 at 16:04
1

You can simply redirect the user changing the variable value and using header()..

if(isset($_GET['variable'] && $_GET['variable'] == 'hello') {
   header('Location: http://site.com/index&variable=world');
   exit;
}
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
0

the variable or parameter in a url is preceded with a ? and then they are separated by &.

To get what you want just use this link:

<a href="http://site.com/index?variable=world&anothervariable=dontchangeme">Click me</a>

but this is hardcoded and not dynamic in the sense that you can change the value of the parameter dynamically so my answer is probably not the best.

martincarlin87
  • 10,848
  • 24
  • 98
  • 145
  • I clarified my answer, I'd like to link to a URL with GET variables without changing other variables already in the URL – tkbx Dec 17 '12 at 16:00
  • But that would still get rid of other variables already in the URL, right? – tkbx Dec 17 '12 at 16:01
  • yes, sorry, I've just read the updated question. My answer is not what you need, I apologise! I will update but it probably won't be as good as deceze's answer – martincarlin87 Dec 17 '12 at 16:03
0

this should do it.

<a href="variable=world <?php foreach ($_GET as $key => $value) {echo '&&'.$key.'='.$value}">Click me</a>
Theolodis
  • 4,977
  • 3
  • 34
  • 53