Tuesday, July 24, 2012

Remove Query From URL Using PHP

I had some free time the past two days, so I've been working on finishing up the the CESAC members area. While I had the Add New Members functionality complete, adding the Edit Existing Member was more interesting.

Given that it's both A, an obscure small site, and B, already password protected, I'm not putting all that much effort into security. Mostly I'm trying to idiot proof it rather than prevent a determined hacker. As such, on pages that should only be accessed in pattern, I'm just grabbing the referrer and validating it against what the previous page should be.

This is fine, until you get start using a single edit page to edit any member. This involves using a query in the URL, the ?ID=somenumber. And this plays hells with my validation. So what is the best way to remove the query? I googled and found a few answers, but all of them use complex filtering, or splitting the URL into pieces and then rebuilding. And since it's rebuilding, the parts that you should include have to be defined. This limits what type of URL you can use without throwing an error.

Instead of building, I'd rather subtract. I'd rather remove the query and leave everything else the same. To this end, the code below solves the problem quite nicely.

$referer = $_SERVER['HTTP_REFERER'];

  $url = parse_url($referer);

  $referer = str_replace('?'.$url['query'],'',$referer);


First we grab the initial full URL. We then break it into an array. And finally, we replace the query with nothing, essentially subtracting it.
 

No comments:

Post a Comment