Accessing $_COOKIE immediately after setcookie()

Viewed 55052

I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE['uname'] isn't set. Why?

Note, however, that $_COOKIE['uname'] is set as expected upon the next execution of the script, such as after a page refresh.

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

I had a similar problem where i used a function from a included file and solved it with a function that both returns the value of the cookie and sets the cookie.

function setCookie($input) {
  setcookie('uname', $input, time() + 60 * 30);
  return $input;
}

if(!isset($_COOKIE['uname'])) {
    $uname  = setCookie($whatever);
} else {
    $uname = $_COOKIE['uname'];
}

echo "Cookie value: " . $uname;
Related