Mayur Buragohain
Mayur Buragohain

Reputation: 1615

$_COOKIE does not fetch updated cookie value

Consider the following code snippet-

    if(some_condition){
        echo $candidate_id= $row_id['id'];
        setcookie("candidate_id", $candidate_id, time()+3600);
        echo "<script>console.log(document.cookie)</script>";
    }
    if(isset($_COOKIE['candidate_id'])){
        echo "from cookie";
        echo $candidate_id= $_COOKIE['candidate_id'];exit;  
    }
    else{
        echo "not from cookie";
        echo $candidate_id= $row_id['id'];exit;
    }

First time it gives a correct output-

 288not from cookie288

and in console,

candidate_id=288; PHPSESSID=kfpjvl9j4rluh1stjdjcijgi75 

But if i again run the code again,i get the following outputs

289from cookie288

and in console,

candidate_id=289; PHPSESSID=kfpjvl9j4rluh1stjdjcijgi75 

This means,on the second run,the cookie value is being modified but $_COOKIE['candidate_id'] is not fetching the updated value. But why?

Upvotes: 0

Views: 150

Answers (1)

elixenide
elixenide

Reputation: 44851

$_COOKIE is initialized based on the cookies in the user's request. It is not updated by calls to setcookie().

You could fake it by doing something like this:

function mySetCookie($name, $value, $time) {
    setcookie($name, $value, $time);
    $_COOKIE[$name] = $value;
}

Then call mySetCookie() wherever you would have called setcookie(). This is possibly buggy, though -- I haven't tested it and am fairly certain it would run into problems in some configurations.

Upvotes: 1

Related Questions