0

So I'm attempting to remove specific parameters from the URL query string that are predefined in an array. Here's what I have so far:

<?php
// Construct the current page URL
$host     = $_SERVER['HTTP_HOST'];
$script   = $_SERVER['SCRIPT_NAME'];
$params   = $_SERVER['QUERY_STRING'];
$currentUrl = 'http://' . $host . $script . '?' . $params;

// Store all URL parameters into an array (HOST, PATH, QUERY, etc)
$url_params = array();
$url_params = parse_url($currentUrl);

// Create an array to store just the query string, breaking them apart
$params_array = explode('&', $url_params['query']);

// Array holding URL parameters that we want to remove
$params_to_remove = array("param1", "param2", "param3", "param4", "param5");


$location = 0;
// Loop through and remove parameters found in PARAMS_TO_REMOVE array
for($x = 0; $x < count($params_to_remove); $x++) {
    if(in_array($params_to_remove[$x], $params_array)) {
        $location = array_search($params_to_remove[$x], $params_array);
        unset($params_array[$location]);
    }
}

// Print array after unwanted parameters were removed
print_r($params_array);
echo '<br /><br />';

// Construct a new array holding only the parameters that we want
$clean_params_array = array();
for($z = 0; $z < count($params_array); $z++) {
    if($params_array[$z] != '') array_push($clean_params_array, $params_array[$z]);
}

// Print clean array
print_r($clean_params_array);
echo '<br />';

// Construct the new URL
// If there are paramters remaining in URL reconstruct them
if(count($clean_params_array) > 0) {
    $final_url = 'http://www.example.com' . $url_params['path'] . '?';
    for($y = 0; $y < count($clean_params_array); $y++) {
        $final_url .= $clean_params_array[$y] . '&';
    }
    // Trim off the final ampersand
    $final_url = substr($final_url, 0, -1);
}
// No parameters in final URL
else $final_url = 'http://www.example.com' . $url_params['path'];

// Print final URL
echo '<br />' . $final_url;
?>

Here's the output:

Using http://www.example.com/test.php?apple&banana&orange&param1&strawberry&param2&pineapple

Array ( [0] => apple [1] => banana [2] => orange [4] => strawberry [6] => pineapple ) 

Array ( [0] => apple [1] => banana [2] => orange [3] => strawberry ) 

http://www.example.com/test.php?apple&banana&orange&strawberry

As you can see I'm losing the last parameter. I also feel as if I'm being too verbose...where am I going wrong?

3
  • 2
    Why don't you use http_build_query() for constructing the URL? Commented Apr 24, 2012 at 20:12
  • Well that doesn't really answer my question... Commented Apr 24, 2012 at 20:28
  • 2
    Therefore I created only a comment, it's just a side note ;) Commented Apr 24, 2012 at 20:29

3 Answers 3

3
$new_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?".implode("&",array_diff(explode("&",$_SERVER['QUERY_STRING']),Array("param1","param2","param3","param4","param5")));

One-liner ;)

Although you'd probably be better off taking that Array(...) out of there and defining it as a variable beforehand, so it's easier to read.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution, but I hate complicated 1 liners like that. I'd rather have 3/4 lines of easy to follow code. So -1, Sorry.
If only I had seen the array_diff function earlier :(
2
<?php 
 /** 
  * generateURL() 
  * 
  * Sprava URL adresy 
  * 
  * @author   stenley <[email protected]> 
  * @version   1.4 
  */ 

 function generateURL() { 
    $GET = $_GET; 
    $QUERY_STRING = ''; 
    $SCRIPT_NAME = substr(strrchr($_SERVER["SCRIPT_NAME"],"/"),1); 

    $num_args = func_num_args(); 
    if($num_args>0 && $num_args%2==0) { 
       $args = func_get_args(); 

       foreach($args as $index => $paramName) { 
          $paramName = trim($paramName); 

          if($index%2==0 && !empty($paramName)) { 
             $paramValue = trim($args[$index+1]); 

             if(array_key_exists($paramName, $GET) && empty($paramValue)) { 
                unset($GET[$paramName]);    
             } elseif(!empty($paramValue)) { 
                $GET[$paramName] = $paramValue; 
             } 
          } 
       } 
    } 

    foreach($GET as $param => $value) { 
       $QUERY_STRING .= $param."=".$value."&amp;"; 
    } 

    return $SCRIPT_NAME.((empty($QUERY_STRING)) ? '' : "?".substr($QUERY_STRING,0,-5)); 
 } 
 ?>

here is great function for managing URL address. usage is easy. here are some examples in Slovak language. but I think you will understand code samples. or I will translate it for you

sorry for my english

Comments

1

Part of the answer is in this line: Array ( [0] => apple [1] => banana [2] => orange [4] => strawberry [6] => pineapple )

Note that $params_array[5] does not exist. Yet you try to read $params_array[5] when $z==5 (In your while loop you go through values $z = 0; => $z < 6; (count($params_array))

You can use Kolink's solution, or use a foreach loop to go through all the values:

foreach($params_array as $param) {
    if($param != '') array_push($clean_params_array, $param); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.