1

I am setting a value to a variable by getting like $value=GET['value']. Now i want to remove the value when i refresh the page. how todo? any help.

below this question also asking same thing, but there I could not find any suitable answer.

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

Community
  • 1
  • 1
Yaseen Ahmed
  • 59
  • 1
  • 4
  • 11
  • 1
    Uhm... remove the variable from the query string a use a Javascript redirect? – Machavity Dec 28 '15 at 19:09
  • if coming the value by javascript redirecting also can not do it. because, anyway again storing the value in php variable only. once fixed the value to the php variable. I could not remove. – Yaseen Ahmed Dec 28 '15 at 19:40

1 Answers1

0

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.

FirstOne
  • 6,033
  • 7
  • 26
  • 45
  • can you put for loop and make complete code. because I am not expert. – Yaseen Ahmed Dec 28 '15 at 19:33
  • @YaseenAhmed, take a look at the edit. This second part might be confusing, but that's what I managed. Also, [foreach](http://php.net/manual/en/control-structures.foreach.php) is the basic to loop `key => value` arrays – FirstOne Dec 28 '15 at 20:02