You are here

array

Removing querystring variables from a URL in PHP

Recently I was trying to remove some variables / keys from a URL in PHP. I wanted a simple function that I could pass a URL and an array of keys to and that would return a modified URL without the keys I specified to have removed. The resulting solution turned out not as simple as I had hoped, but here it is anyway:

function remove_querystring_vars($url, $keys) {

$url = parse_url($url);

parse_str($url['query'], $query);

foreach ($keys as $key) {
unset($query[$key]);
}

$url['query'] = http_build_query($query);

$value = glue_url($url);

return $value;

}

// $parsed is a parse_url() resulting array
function glue_url($parsed) {

if (! is_array($parsed)) return false;

if (isset($parsed['scheme'])) {
$sep = (strtolower($parsed['scheme']) == 'mailto' ? ':' : '://');
$uri = $parsed['scheme'] . $sep;
} else {
$uri = '';
}

if (isset($parsed['pass'])) {
$uri .= "$parsed[user]:$parsed[pass]@";
} elseif (isset($parsed['user'])) {
$uri .= "$parsed[user]@";
}

if (isset($parsed['host'])) $uri .= $parsed['host'];
if (isset($parsed['port'])) $uri .= ":$parsed[port]";
if (isset($parsed['path'])) $uri .= $parsed['path'];
if (isset($parsed['query'])) $uri .= "?$parsed[query]";
if (isset($parsed['fragment'])) $uri .= "#$parsed[fragment]";

return $uri;
}

?>

Basically, its two functions. The first function called remove_querystring_vars expects the url and a simple array of keys to be passed to it. The second function glue_url is required as a helper function to re-assemble the url after its dismantled. Unfortunately, there isn't an opposite function to parse_url built into the PHP library so this function is required.

Here is a sample usage:

<?php

$keys = array("foo", "foo2");
$url = "http://www.myurl.com/somepage.php?key=value&foo=bar&foo2=bar2&key2=value2";
print remove_querystring_vars($url, $keys);

?>

This should return:


http://www.myurl.com/somepage.php?key=value&key2=value2