phprequest-uri

PHP: Change URL parameter


This is what I have

echo '<button><a href="'.$_SERVER['REQUEST_URI'].'&startrow='.($startrow+100).'">Next 100</a></button>';

I have 2 parameters in my url one is campaign, second is startrow, how can I just remove 'startrow' parameter and its value from the url. I want something like this.

echo '<button><a href="'.REMOVE &startrow=x($_SERVER['REQUEST_URI']).'&startrow='.($startrow+100).'">Next 100</a></button>';

When I press the next 100 button, the page reloads and it adds startrow parameter in the url hence if I pressed next 100 button 5 times, I have 5 startrow paramter in the url, so I want to remove the previous startrow parameter first then add the new one

My actual url: enquirytable.php/campaign=all&startrow=100

When I click on Next 100 button: enquirytable.php/campaign=all&startrow=100&startrow=200

What I want: enquirytable.php/campaign=all&startrow=200


Solution

  • Probably the long one, but an accurate way. Here we are using parse_url and parse_str to achieve desired output.

    Try with an example

    <?php
    
    $url="http://www.example.com/some/path?startrow=100&campaign=abc";
    echo change_url_parameter($url, "startrow", 200);
    
    function change_url_parameter($url,$parameterName,$parameterValue) {
        $url=parse_url($url);
        parse_str($url["query"],$parameters);
        unset($parameters[$parameterName]);
        $parameters[$parameterName]=$parameterValue;
        return  sprintf("%s://%s%s?%s", 
            $url["scheme"],
            $url["host"],
            $url["path"],
            http_build_query($parameters));
    }