rockyraw
rockyraw

Reputation: 1145

Strip Two parameters from URL

I have the following code which checks for any parameter that begins with xz, and if it finds such a paramater, it will redirect to the same page only without such parameters:

function unparse_url($parsed_url) {
  $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
  $pass     = ($user || $pass) ? "$pass@" : '';
  $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  $query    = !empty($parsed_url['query']) ? '?' . trim($parsed_url['query'], '&') : '';
  $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  return "$scheme$user$pass$host$port$path$query$fragment";
}

function strip_query($url, $query_to_strip) {
  $parsed = parse_url($url);
  $parsed['query'] = preg_replace('/(^|&)'.$query_to_strip.'[^&]*/', '', $parsed['query']);
  return unparse_url($parsed);
}

$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";


$new_url = (strip_query($url, 'xz')); # or whatever query you want to strip/keep


$filtered = array_filter(array_keys($_GET), function($k) {
    return strpos($k, 'xz') === 0;
});

if ( !empty($filtered) ) {
    header ("Location: $new_url");
}

Example:

User that lands on: domain.com/?xz=1&a=2&xzbo=3 will be redirected to domain.com/?a=2

How can I do this for 2 different parameter patterns, for example, anything that start with xz plus anything that starts with ab?

Upvotes: 0

Views: 74

Answers (1)

Kevin Nagurski
Kevin Nagurski

Reputation: 1889

A simple fix might be to define a new function strip_queries.

/**
 * @param string $url
 * @param array  $queries the query params to strip
 * @return string
 */
function strip_queries($url, array $queries)
{
    foreach ($queries as $query) {
        $url = strip_query($url, $query);
    }

    return $url;
}

And call with

$new_url = strip_queries($url, array('xz', 'ab'));

You really should look into http_build_query and parse_url as well. With those you can manage the query params as an array instead of with string manipulation.

Upvotes: 1

Related Questions