This code removes everything from _GET
:
// Need to check to prevent loop
if(empty($_GET)){
// DO SOMETHING ON SECOND LOAD AFTER REMOVING
}else{
// Do something with _GET before removing
header('Location: ' . basename(__FILE__));
}
If removing specific values from GET is what you want, use is my little beast (this code allows you to do something before removing):
// Removes $arr keys from GET
function removeGETKeys($arr = array()){
$tmp = array();
foreach($arr as $v){
$tmp[$v] = '';
}
return array_diff_key($_GET, $tmp);
}
// Checks if the keys are already removed
function checkRemoved($arr = array()){
foreach($arr as $v){
if(array_key_exists($v, $_GET)){
return false;
}
}
return true;
}
// The keys to remove from GET
$remove = array('foo', 'bar');
// Prevent page loop
if(checkRemoved($remove)){
// Do something on second load AFTER removing
echo 'Result: <br>';
print_r($_GET);
}else{
// Do something with _GET BEFORE removing
$removed = removeGETKeys($remove);
$path = basename(__FILE__);
$i = 0;
// recreate the keys
foreach($removed as $k => $v){
$path .= $i==0 ? "?$k=$v" : "&$k=$v";
$i++;
}
// redirects without the selected keys
header('location: ' . $path);
}
Example link:
t1.php?foo=123&bar=123&value=123
Final link:
t1.php?value=123
Final page content:
Result:
Array ( [value] => 123 )
I tested this in different ways but might still bug.
Tested the following:
- GET params that aren't in the
$remove
list: ✓
- Removing no GET params (
$remove
!= GET
): ✓
- Removing all
$remove
from GET
: ✓
- Empty
$remove
: ✓
- Empty
GET
: ✓
All theses tests seem to work as expected. If you see any mistakes, let me know, please.