Eileen
Eileen

Reputation: 6660

How to use $_SERVER['REQUEST_URI'] to write a new URL and not infinitely-loop?

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&sort=name , which works perfectly.

But then once I am on the page http://domain.com/listings&sort=name, the link on the page is written to http://domain.com/listings&sort=name&sort=name. Additionally, if I click one of the other sorting links I will end up with http://domain.com/listings&sort=name&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.)

Upvotes: 0

Views: 563

Answers (1)

Artefacto
Artefacto

Reputation: 97835

One common strategy is to do something like:

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

to calculate the new query string.

Upvotes: 1

Related Questions