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'];
The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.
For instance, time()+60*60*24*30 will set the cookie to expire in 30 days. Another option is to use the mktime() function. If set to 0 , or omitted, the cookie will expire at the end of the session (when the browser closes).
PHP Create/Retrieve a Cookie The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With