tags:

views:

52

answers:

3

I'm trying to access cookie value (using $_COOKIE) immediately after setcookie() function in PHP. But, $_COOKIE['uname'] returns blank. Why?

Whereas, $_COOKIE['uname'] returns actual value when trying to access in next execution of the script.

setcookie('uname', $uname, time()+60*30);
echo "Cookie value: ".$_COOKIE['uname'];
+4  A: 

$_COOKIE is set when the page loads, due to the stateless nature of the web. If you want immediate access, you stuff set $_COOKIE['uname'] yourself or use an intermediate variable.

Something like this could work:

if (isset($_COOKIE['uname'])) {
    // get data from cookie for local use
    $uname = $_COOKIE['uname'];
}
else {
    // set cookie, local $uname already set
    setcookie('uname', $uname, time()+60*30);   
}
Jason McCreary
+2  A: 

The cookie isn't set until the response is sent back to the client, and isn't available in your PHP until the next request from the client after that.

However, when you set the cookie in your script, you can do:

setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;
Mark Baker
A: 

If you set a cookie, it will be send with the HTTP HEADER to the browser. On the next request, the browser sends his request including the cookie data. So before sending it to the browser and getting it back in the next response, it is not stored in the $_COOKIE variable.

Kau-Boy