Is there any difference between setting a cookie via setcookie()
and $_COOKIE
?
Sometimes,when setting a cookie via setcookie
,i don't get the value of that cookie via $_COOKIE['cookie_name'].But js console.log immediately after setcookie
,shows that cookie is set but if i try to get the value of the cookie via $_COOKIE,i don't get the updated value.
I'm confused..!!
Introduction. The superglobal $_COOKIE stores variables passed to current script along with HTTP request in the form of cookies. $HTTP_COOKIE_VARS also contains the same information, but is not a superglobal, and now been deprecated.
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.
There are two types of cookies, they are: Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the browser is closed. Persistent Cookie: To make a cookie persistent we must provide it with an expiration time.
Cookies must be sent before any HTML is sent to the page or they do not work, so the setcookie() function must appear before the <html> tag.
You can't actually "set" a cookie with some code like this:
$_COOKIE['cookie'] = $my_var;
All this does is add a new value to the $_COOKIE
array. No Set-Cookie
HTTP header is sent back to the client (browser) in the response and no cookie will be created on the client.
Use the setcookie()
function to set cookies.
The current accepted answer correctly points out that $_COOKIE
is set/initialized at the start of the PHP process and isn't updated after that. You can update it yourself but don't expect that value to stick on the next request.
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