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 t
When calling setcookie, PHP sets an HTTP Cookie header that's delivered to the client together with the rest of the output of the script. The client (browser) will then store this cookie in its cookie storage and send it back to the server on subsequent requests.
$_COOKIE contains all the cookies that have been received in the current request from the client. The first time that's nothing, since the client hasn't received the Cookie header yet. Only on subsequent requests does the client send the cookie which gets stored in $_COOKIE. setcookie() does not populate the $_COOKIE variable.
Client Server
1. --> $_COOKIE is empty
2. Cookie
store <-- setcookie()
3. Cookie
send --> $_COOKIE is set