When the following code is run for the first time, it does not echo out the “var1” value but it does on browser refresh (f5), Why? As i understand when the browser sends the code to the server, setcookie() stores the cookie variable (“var1”) to a client (browser) in a local file and puts the “var1” value available in global domain via $_COOKIE superglobal.
Since “var1” value is available immediately in $_COOKIE after the first server replies to browser’s initial request, then why the “var1” is not echoed out. Is it that setcookie() stores “var1” value in client’s browser on first request and only when the page is refreshed (2nd request) the browser sends back “var1” value to the server and then the server makes it available in the global domain via $_COOKIE function.
CODE
<?php
setcookie("var1","5");
echo $_COOKIE['var1'];
?>
Kindly clear this for me.
Thanks
djain.
It’s all explained in the manual.
setcookie()causes aSet-Cookie:response header to be returned to the browser. The$_COOKIEarray can only be filled with the next HTTP refresh when the browser had the opportunity to reply back with theCookie:request header.The browser needs to send the cookie back. On the first request it doesn’t know about that cookie yet. After the refresh it does. Only then it can send it.
On the second request.
The browser saves it.
Not immediately.
It is not immediately in $_COOKIE. It can’t be. That array is only populated once, when PHP starts.
Yes. That’s how it works.