tags:

views:

24

answers:

2

I have a php page and want to write a link that is based on the current URL. Like so:

$alias = substr(strrchr($_SERVER['REQUEST_URI'], "/"), 1);

print '<a href="'.$alias.'&sort=name">Sort by Name</a>';

On the page http://domain.com/listings , the link is written to http://domain.com/listings&amp;sort=name , which works perfectly.

But then once I am on the page http://domain.com/listings&amp;sort=name, the link on the page is written to http://domain.com/listings&amp;sort=name&amp;sort=name. Additionally, if I click one of the other sorting links I will end up with http://domain.com/listings&amp;sort=name&amp;sort=comments .

That is dorky. Is there a better way to generate my link? Or should I do something to clean $alias before I reuse it? Complication: There are some variables (like &category=34 and &title=spa) that I don't want to remove from the URL, so I can't just clean it back to /listings.

(I am using Drupal, if there are secret variables built in there that would be cool too.)

A: 

Try $_SERVER['SCRIPT_NAME'] instead. The REQUEST_URI always includes the query string.

BoltClock
+1  A: 

One common strategy is to do something like:

http_build_query(array_merge($_GET, array("sort" => "name")))

to calculate the new query string.

Artefacto
Eileen