heapzero heapzero - 4 years ago 627
PHP Question

Accessing $_COOKIE immediately after setcookie()

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'];

Answer Source

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

For example:

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() + 1800);  
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download