PHP - Working of Cookies

家住魔仙堡 提交于 2020-01-06 07:01:16

问题


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).



来源:https://stackoverflow.com/questions/12529469/php-working-of-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!