26

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!

4
  • 1
    use preg_replace on $_SERVER["REQUEST_URI"] if d= exists Commented Apr 16, 2013 at 12:16
  • @Robert Podwika.I think that preg_replace will do but i don't know how to use that code, for now I will study that at manual of PHP. Thanks. I will hit +1 if the code fix my problem.Thanks Robert! Commented Apr 16, 2013 at 12:24
  • @kodewrecker: Have you check out my answer? It should work Commented Apr 16, 2013 at 12:39
  • should $c=3 be &c=3 instead, right? Commented Mar 12, 2014 at 7:29

8 Answers 8

69
$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>
Sign up to request clarification or add additional context in comments.

4 Comments

This is a way better answer, I was looking for something like this. Thanks.
By far the most elegant solution I have seen posted across several similar questions
If rewriting of URLs is enabled (for example mod_rewrite), PHP_SELF will return the actual php file name, not the one seen in the url bar. It should work, but the link will change the path in the url bar.
This answer as written is insecure and will produces an XSS vulnerability.See cheatsheetseries.owasp.org/cheatsheets/…
6

Try with the below expression, It Should Work

preg_replace("#&d=.*&#", '&d=newvalue&', $_SERVER['REQUEST_URI'])

3 Comments

yeah I am testing it right now. what is with the first parameter? "#&d=.*&#" is the number sign(#) and asterisk(*) is necessary? could i ask what is that for?
Those are expression syntax. '&d=.*&' this is the thing what we want. It will replace the content &d=*& with what u give as second param. I have updated the code please check it again with new code.
Note to anybody finding this answer and trying it. This will NOT work if the variable you wish to change is the first variable due to the missing '&' sign in front.
6
modify_url_query($url, array('limit' => 50));

My function for modifying query in url

function modify_url_query($url, $mod){

$purl = parse_url($url);

$params = array();

if (($query_str=$purl['query']))
{
    parse_str($query_str, $params);

    foreach($params as $name => $value)
    {
        if (isset($mod[$name]))
        {
            $params[$name] = $mod[$name];
            unset($mod[$name]);
        }
    }
}        

$params = array_merge($params, $mod);

$ret = "";

if ($purl['scheme'])
{
    $ret = $purl['scheme'] . "://";
}    

if ($purl['host'])
{
    $ret .= $purl['host'];
}    

if ($purl['path'])
{
    $ret .= $purl['path'];
}    

if ($params)
{
    $ret .= '?' . http_build_query($params);
}    


if ($purl['fragment'])
{
    $ret .= "#" . $purl['fragment'];
}        

return $ret;

}

1 Comment

It was working but getting undefined errors, how to fix that?
6

To remove repeated addition of query parameter do the below

// parse the url
$pathInfo = parse_url($_SERVER['REQUEST_URI']);
$queryString = $pathInfo['query'];
// convert the query parameters to an array
parse_str($queryString, $queryArray);
// add the new query parameter into the array
$queryArray['d'] = 1;
// build the new query string
$newQueryStr = http_build_query($queryArray);

// construct new url
?>
<a href="<?php echo $pathInfo['host'].'?'.$newQueryStr;?>">LINK 1</a>

1 Comment

@CaffeineShots it should be parse_str($queryString, $queryArray); instead of $queryArray = parse_str($queryString); and $data is then $queryArray
3
function replaceUrlParameters($url = '', $newParams = array()){
    if($url){
        $urlArray = parse_url($url);
        $queryString = $urlArray['query'];
        parse_str($queryString, $queryParams);
        $queryParams = array_merge($queryParams, $newParams);
        $urlArray['query'] = http_build_query($queryParams);

        if(!empty($urlArray)){
            $url = $urlArray['scheme'].'://'.$urlArray['host'].$urlArray['path'].'?'.$urlArray['query'];
        }
    }
    return $url;
}
// $newParams = array of new parameters or old parameters with new value
$replacedUrl = replaceUrlParameters($url, $newParams);

Suppose you have url like :- <?php echo $_SERVER["REQUEST_URI"]."&a=test1&b=test2";?> and you want to replace parameter b's value to test3 then just pass this url and an array with the same index with new value. for ex- <?$url = $_SERVER["REQUEST_URI"]."&a=test1&b=test2";?> <? $newParams = ['b' => 'test3']?> then you will get - <? $_SERVER["REQUEST_URI"]."&a=test1&b=test3";?>

2 Comments

Please consider to explain what this code snippet does, and how to work with it. How does this solve the problem in the original question?
Edited my answer.
0

Here you have not take care of the double quotation. Replace that with the following code and then check.

<a href="<?php echo 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].'&d=test1';?>">LINK 1</a>

And also check in firebug that what URL is in href each time.

2 Comments

I don't think that would make any difference?
@OSSCube.I tried it,in my end both double quote and single is doing fine,however I change it just to test your's, still reproducing the variable d sir, but thanks for reply anyway.
0

Couldn't still find fitting solution myself, so created one..

static function changeParameters($url, $parameters)
{
    $urlParts = parse_url($url);


    $url = "";

    if (isset($urlParts['scheme'])) {
        $url .= $urlParts['scheme'] . "://";
    }

    if (isset($urlParts['host'])) {
        $url .= $urlParts['host'];
    }

    if (isset($urlParts['path'])) {
        $url .= $urlParts['path'];
    }

    $query = isset($urlParts['query']) ? $urlParts['query'] : "";

    $urlParameters = explode("&", $query);

    $urlParameterValuesByKey = new stdClass();

    foreach ($urlParameters as $urlParameter) {
        $equalsIndex = strrpos($urlParameter, "=");

        if ($equalsIndex) {
            $urlParameterValuesByKey->{substr($urlParameter, 0, $equalsIndex)} = substr($urlParameter, $equalsIndex + 1);
        } else {
            $urlParameterValuesByKey->{$urlParameter} = null;
        }
    }

    foreach ($parameters as $key => $value) {
        if(!is_string($value)) {
            unset($urlParameterValuesByKey->{$key});
        } else {
            $urlParameterValuesByKey->{$key} = $value;
        }
    }

    $query = "";

    foreach ($urlParameterValuesByKey as $key => $value) {
        if (strlen($query) === 0) {
            $query .= "?";
        }

        if (strlen($query) > 1) {
            $query .= "&";
        }
        if (is_string($value)) {
            $query .= $key . "=" . $value;
        } else {
            $query .= $key;
        }
    }


    $url .= $query;

    return $url;
}

Uses stdClass instead of associative array, because associative arrays does some funky stuff for the keys before setting them, as described here.

Comments

0
//for absolute path of the page. 
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
//first delete the param 
$url = str_replace('&d='.$_GET["d"], '', $actual_link); 
//Now add this param again with it new value
$newUrl=$url.'&d=NewValueHere';
echo '<a href="'.$newUrl.'">Refresh to get new param value</a>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.