Php does not add url parameter that already exists

In php, I add an extra URL segment ?sort to sort messages in ascending or descending order.

  <?php //get current URL $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; //filter URL and create sorting links if(filter_var($url, FILTER_VALIDATE_URL)) { ?> <a href="<?php echo $url; ?>?sort=asc">Small</a> <a href="<?php echo $url; ?>?sort=desc">Large</a> <?php } ?> 

Problem: every time I click the link, the URL segment repeats in the URL.

Example: http://mysite.com/another_segment/?sort=asc?sort=asc?sort=asc

To prevent repeating, how do I replace a URL segment when I click one of two sort links? I do not need to separate the parameters with the & characters. I expect only one separator. I use it in a paginated script, so the parameter should remain in the url when browsing the pages.

I am also trying to avoid javascript

+4
source share
5 answers

You must use the following function to remove the sort key in an existing URL and then add.

 function remove_querystring_var($url, $key) { $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); $url = substr($url, 0, -1); return $url; } 

Your code should change this way

  <?php //get current URL $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $url = remove_querystring_var($url, "sort"); //filter URL and create sorting links if(filter_var($url, FILTER_VALIDATE_URL)) { ?> <a href="<?php echo $url; ?>?sort=asc">Small</a> <a href="<?php echo $url; ?>?sort=desc">Large</a> <?php } ?> 
+3
source

Reset the request with $url and rebuild $_GET with & .

 $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // Strip the query string from URL list($url,) = explode('?', $url); // Remove 'sort' from querystring if exist if (isset($_GET['sort'])) unset($_GET['sort']); // Rebuild query string, append with '&' $url .= '?'. http_build_query($_GET).(count($_GET) ? '&' : ''); if (filter_var($url, FILTER_VALIDATE_URL)) { ?> <a href="<?php echo $url; ?>sort=asc">Small</a> <a href="<?php echo $url; ?>sort=desc">Large</a> <?php } ?> 

That way you can have urls with querystring parameters, but only one sort=asc|desc :

 http://example.com/some/path?page=1&last=1500&sort=asc http://example.com/some/path?page=1&last=1500&sort=desc 
+2
source

To remove a query string from $_SERVER['REQUEST_URI'] , use $URI = strstr($_SERVER['REQUEST_URI'], "?", true); .

Link: php.net ;

+1
source
 <?php $get_asc = $get_desc = $_GET; $get_asc['sort'] = 'asc'; $get_desc['sort'] = 'desc'; if(filter_var($url, FILTER_VALIDATE_URL)) { ?> <a href="<?php echo $url . '?' . http_build_query($get_asc); ?>">Small</a> <a href="<?php echo $url . '?' . http_build_query($get_desc); ?>">Large</a> <?php } ?> 
+1
source

Try using $_SERVER['SCRIPT_NAME'] instead of REQUEST_URI .

0
source

All Articles