How to get and change URL variable PHP

2020-02-25 06:17发布

问题:

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!

回答1:

$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>


回答2:

Try with the below expression, It Should Work

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


回答3:

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;

}


回答4:

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>


回答5:

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";?>



回答6:

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.



回答7:

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.