Monday, August 16, 2010

How to remove unused GET parameters from a page's URL

I've several pages that accept numerous GET parameters from the URL, but sometimes few if any of these parameters are provided. I want to strip the blank parameters from the URL and direct the browser to that link, so that the URL is more readable, and so that users may copy and paste or bookmark a more concise URL.

Near the top of my PHP script I call the shrink_url() function, which I have preloaded with a require_once("funcs.php") statement.  funcs.php includes this function:

function shrink_url()
{
    $currenturl =curPageURL();
    $servername = $_SERVER["SERVER_NAME"];
    $scriptname = $_SERVER["SCRIPT_NAME"];
    foreach ($_GET as $key => $value)
    {
        if ($value <> "") {$getparams .= "&" . $key . "=" . urlencode($value);}
    }
    $getparams = substr($getparams,1);
    if ($getparams <> "") $getparams = "?" . $getparams;
    $redirect = "http://" . $servername . $scriptname . $getparams;
    if ($currenturl <> $redirect)
    {
        ob_end_clean(); //stops loading the current page.
        header("Location: $redirect"); //redirects to the shrunken URL.
    }
}

No comments:

Post a Comment

Constructive, concise comments are welcome.