Search code examples
phpurlget

PHP unset get parameter?


 function getUrlCurrently() {
    $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";

if ($_SERVER["SERVER_PORT"] != "80")  {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}  else  {
   $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}

I'm using this function to determine the current URL of the page. I want to know if it is possible to extend this function to unset a pre-determined $_GET parameter.

All of my $_GET values are stored in an array. So I can access the specific values by using

$my_array[0]

Is it expensive and not realistic to use my suggested logic to accomplish this task?

EDIT: I only want to print the URL to use it as a link.
My url has GET parameters in it.


Solution

  • Update to your function:

    function getUrlCurrently($filter = array()) {
        $pageURL = isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on" ? "https://" : "http://";
    
        $pageURL .= $_SERVER["SERVER_NAME"];
    
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= ":".$_SERVER["SERVER_PORT"];
        }
    
        $pageURL .= $_SERVER["REQUEST_URI"];
    
    
        if (strlen($_SERVER["QUERY_STRING"]) > 0) {
            $pageURL = rtrim(substr($pageURL, 0, -strlen($_SERVER["QUERY_STRING"])), '?');
        }
    
        $query = $_GET;
        foreach ($filter as $key) {
            unset($query[$key]);
        }
    
        if (sizeof($query) > 0) {
            $pageURL .= '?' . http_build_query($query);
        }
    
        return $pageURL;
    }
    
    // gives the url as it is
    echo getUrlCurrently();
    
    // will remove 'foo' and 'bar' from the query if existent
    echo getUrlCurrently(array('foo', 'bar'));