PHP - Working of Cookies

2019-08-17 05:42发布

问题:

I am facing a difficulty in understanding the usage of cookies in PHP, Please consider the following code snippet

 public function preExecute() {

setcookie("testCookie", "Hello123", time() + 31536000, "/", WebServer::getServerName());
echo "Before Value of cookine in decommission::".$_COOKIE["testCookie"];
setcookie("testCookie", "Hello456", time() + 31536000, "/", WebServer::getServerName());
echo "After Value of cookine in decommission::".$_COOKIE["testCookie"];
}

The output that i am expecting for this code

Before Value of cookine in decommission::Hello123

After Value of cookine in decommission::Hello456

But the output i am getting for the above code snippet is

Before Value of cookine in decommission::Hello456

After Value of cookine in decommission::Hello456

Will appreciate if someone explain me the working, i have gone through resources available in internet, but still i am not clear.

Thanks in advance.

回答1:

$_COOKIE holds the cookies that have been received in the current request. It is not automatically updated when you call setcookie to set cookies in your response. The cookies you set via setcookie will only appear in $_COOKIE on the next request, when the cookies are sent back to the server.

So what you're seeing is that the second cookie overwrites the first, so only the later value is sent back to the server. I'll guess you have refreshed the page several times already, so you're seeing the cookie. If you clean your cookies and run this again, on the first try you won't see any output, because $_COOKIE is empty and stays empty for the whole request, no matter how often you call setcookie.



回答2:

If you dont want to change this usage, use sessions. $_SESSION is a global array. You can reach from everywhere (inside class,function) and use instantly (no need to wait next request/page load).