[php] Strip off URL parameter with PHP

I have some links in a powerpoint presentation, and for some reason, when those links get clicked, it adds a return parameter to the URL. Well, that return parameter is causing my Joomla site's MVC pattern to get bungled.

So, what's an efficient way to strip off this return parameter using PHP...?

Example: http://mydomain.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0

This question is related to php

The answer is


Here is the actual code for what's described above as the "the safest 'correct' method"...

function reduce_query($uri = '') {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        return $new_uri;
    }
    return $uri;
}

$_SERVER['REQUEST_URI'] = reduce_query($_SERVER['REQUEST_URI']);

However, since this will likely exist prior to the bootstrap of your application, you should probably put it into an anonymous function. Like this...

call_user_func(function($uri) {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        // Update server variable.
        $_SERVER['REQUEST_URI'] = $new_uri;

    }
}, $_SERVER['REQUEST_URI']);

NOTE: Updated with urldecode() to avoid double encoding via http_build_query() function. NOTE: Updated with ksort() to allow params with no value without an error.


Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!

Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)

<?php

function currenturl_without_queryparam( $queryparamkey ) {
    $current_url = current_url();
    $parsed_url = parse_url( $current_url );
    if( array_key_exists( 'query', $parsed_url )) {
        $query_portion = $parsed_url['query'];
    } else {
        return $current_url;
    }

    parse_str( $query_portion, $query_array );

    if( array_key_exists( $queryparamkey , $query_array ) ) {
        unset( $query_array[$queryparamkey] );
        $q = ( count( $query_array ) === 0 ) ? '' : '?';
        return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
    } else {
        return $current_url;
    }
}

function current_url() {
    $current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
    return $current_url;
}

echo currenturl_without_queryparam( 'key' );

?>

Procedural Implementation of Marc B's Answer after refining Sergey Telshevsky's Answer.

function strip_param_from_url( $url, $param )
{
    $base_url = strtok($url, '?');              // Get the base url
    $parsed_url = parse_url($url);              // Parse it 
    $query = $parsed_url['query'];              // Get the query string
    parse_str( $query, $parameters );           // Convert Parameters into array
    unset( $parameters[$param] );               // Delete the one you want
    $new_query = http_build_query($parameters); // Rebuilt query string
    return $base_url.'?'.$new_query;            // Finally url is ready
}

// Usage
echo strip_param_from_url( 'http://url.com/search/?location=london&page_number=1', 'location' )

function removeParam($url, $param) {
    $url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*$/', '', $url);
    $url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*&/', '$1', $url);
    return $url;
}

This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number

<?php
$x = 'http://url.com/search/?location=london&page_number=1';

$parsed = parse_url($x);
$query = $parsed['query'];

parse_str($query, $params);

unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);

@MarcB mentioned that it is dirty to use regex to remove an url parameter. And yes it is, because it's not as easy as it looks:

$urls = array(
  'example.com/?foo=bar',
  'example.com/?bar=foo&foo=bar',
  'example.com/?foo=bar&bar=foo',
);

echo 'Original' . PHP_EOL;
foreach ($urls as $url) {
  echo $url . PHP_EOL;
}

echo PHP_EOL . '@AaronHathaway' . PHP_EOL;
foreach ($urls as $url) {
  echo preg_replace('#&?foo=[^&]*#', null, $url) . PHP_EOL;
}

echo PHP_EOL . '@SergeS' . PHP_EOL;
foreach ($urls as $url) {
  echo preg_replace( "/&{2,}/", "&", preg_replace( "/foo=[^&]+/", "", $url)) . PHP_EOL;
}

echo PHP_EOL . '@Justin' . PHP_EOL;
foreach ($urls as $url) {
  echo preg_replace('/([?&])foo=[^&]+(&|$)/', '$1', $url) . PHP_EOL;
}

echo PHP_EOL . '@kraftb' . PHP_EOL;
foreach ($urls as $url) {
  echo preg_replace('/(&|\?)foo=[^&]*&/', '$1', preg_replace('/(&|\?)foo=[^&]*$/', '', $url)) . PHP_EOL;
}

echo PHP_EOL . 'My version' . PHP_EOL;
foreach ($urls as $url) {
  echo str_replace('/&', '/?', preg_replace('#[&?]foo=[^&]*#', null, $url)) . PHP_EOL;
}

returns:

Original
example.com/?foo=bar
example.com/?bar=foo&foo=bar
example.com/?foo=bar&bar=foo

@AaronHathaway
example.com/?
example.com/?bar=foo
example.com/?&bar=foo

@SergeS
example.com/?
example.com/?bar=foo&
example.com/?&bar=foo

@Justin
example.com/?
example.com/?bar=foo&
example.com/?bar=foo

@kraftb
example.com/
example.com/?bar=foo
example.com/?bar=foo

My version
example.com/
example.com/?bar=foo
example.com/?bar=foo

As you can see only @kraftb posted a correct answer using regex and my version is a little bit smaller.


$var = preg_replace( "/return=[^&]+/", "", $var ); 
$var = preg_replace( "/&{2,}/", "&", $var );

Second line will just replace && to &


In a different thread Justin suggests that the fastest way is to use strtok()

 $url = strtok($url, '?');

See his full answer with speed tests as well here: https://stackoverflow.com/a/1251650/452515


You could do a preg_replace like:

$new_url = preg_replace('/&?return=[^&]*/', '', $old_url);

This one of many ways, not tested, but should work.

$link = 'http://mydomain.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0';
$linkParts = explode('&return=', $link);
$link = $linkParts[0];

Remove Get Parameters From Current Page

<?php
$url_dir=$_SERVER['REQUEST_URI']; 

$url_dir_no_get_param= explode("?",$url_dir)[0];

echo $_SERVER['HTTP_HOST'].$url_dir_no_get_param;

<? if(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>

This will remove the 'i' parameter from the URL. Change the 'i's to whatever you need.


function remove_attribute($url,$attribute)
 {
    $url=explode('?',$url);
    $new_parameters=false;
    if(isset($url[1]))
    {
        $params=explode('&',$url[1]);
        $new_parameters=ra($params,$attribute);
    }
    $construct_parameters=($new_parameters && $new_parameters!='' ) ? ('?'.$new_parameters):'';
    return $new_url=$url[0].$construct_parameters;
 }
 function ra($params,$attr)
    {   $attr=$attr.'=';
        $new_params=array();

        for($i=0;$i<count($params);$i++)
        {   
            $pos=strpos($params[$i],$attr);

            if($pos===false)
            $new_params[]=$params[$i];

        }
        if(count($new_params)>0)
        return implode('&',$new_params);
        else 
        return false; 
     }

//just copy the above code and just call this function like this to get new url without particular parameter

echo remove_attribute($url,'delete_params'); // gives new url without that parameter


parse_str($queryString, $vars);
unset($vars['return']);
$queryString = http_build_query($vars);

parse_str parses a query string, http_build_query creates a query string.


very simple

$link = "http://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0"
echo substr($link, 0, strpos($link, "return") - 1);
//output : http://example.com/index.php?id=115&Itemid=283

This should do it:

public function removeQueryParam(string $url, string $param): string
{
    $parsedUrl = parse_url($url);

    if (isset($parsedUrl[$param])) {
        $baseUrl = strtok($url, '?');
        parse_str(parse_url($url)['query'], $query);
        unset($query[$param]);
        return sprintf('%s?%s',
            $baseUrl,
            http_build_query($query)
        );
    }

    return $url;
}