0

I am having an issue where after first clicking Submit, and the page reloads, the page shows the old value for each cookie set until the page is refreshed or reloaded.

Here is essentially how I have it set up.

index.php

<?php 
    if(isset($_POST['filter'])){
        foreach($_POST['filter'] as $key=>$value){
            $xNums[] = $key;    
        }
        $vals = $_POST['filter'];
        updateFilter($vals, $xNums);
    }
?>
<form action='index.php' method='post'>
<input type='radio' name=filter['".$xNum."'] value='yes' />Show<input type='radio' name=filter['".$SomeVariable."'] value='no' />Hide
<input type=submit value=" Submit " />
<?php
    echo displayStatus($xNum);
?>

functions.php

function updateFilter($vals, $xNums){
    foreach($xNums as $xNum){
        $val = $vals[$xNum];
        setcookie($xNum, $val, time()+3600);
    }
    return;
}

function displayStatus($xNum){
    if($_COOKIE["'".$xNum."'"]=='no'){
        return "no";
    } else {
        return "yes";
    }
}
EliteTech
  • 386
  • 3
  • 13

1 Answers1

5

The cookie which you set using setcookie is not visible by PHP script in $_COOKIES superglobal variable until next request because setcookie only set Set-Cookie header in http response.

If you want to read these cookies in the same request you can use:

setcookie($xNum, $val, time()+3600);
$_COOKIE[$xNum] = $val;

edit: here is similar problem.

Community
  • 1
  • 1
rzymek
  • 866
  • 7
  • 20