Skip to content
Advertisement

How to get and change URL variable PHP

Hi could anyone help me with this I have a URL like

parent/child/a=1&b=2$c=3

then I have a link that would add variable to that URL

<a href="<?php echo $_SERVER["REQUEST_URI"]."&d=test1";?>">LINK 1</a>
<a href="<?php echo $_SERVER["REQUEST_URI"]."&d=test2";?>">LINK 2</a>

every time I click my link the variable d to URL keep on reproducing like this

parent/child/a=1&b=2&c=3&d=test2&d=test2&d=test2&d=test1&d=test1

I know that the $_SERVER[“REQUEST_URI”] keep getting the current URL that is why I get that result. I have tried the some of properties of $_SERVER[“”]. What I like is to change the d variable value, any idea how to do it. Any response is well appreciated.Thanks!

Advertisement

Answer

$query = $_GET;
// replace parameter(s)
$query['d'] = 'new_value';
// rebuild url
$query_result = http_build_query($query);
// new link
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?<?php echo $query_result; ?>">Link</a>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement