Are newly created cookies not available until a subsequent page load?

这一生的挚爱 提交于 2019-12-10 23:54:18

问题


When I first create a cookie I don't seem to be able to grab that same cookie until a subsequent page load. It's as if the cookie doesn't exist to the browser until the page is requested a second time.

I'm using the Kohana PHP framework:

Cookie::set('new_cookie', 'I am a cookie');
$cookie = Cookie::get('new_cookie');
//$cookie is NULL the first time this code is run. If I hit the page again
and then call Cookie:get('new_cookie'), the cookie's value is read just fine.

So, I'm led to believe that this is normal behavior and that I probably don't understand how cookies work. Can anyone clarify this for me?


回答1:


Cookies are set in HTTP headers, so when the server returns the page. When you reload the page, your browser will send them back to the server.

So, it is perfectly normal they are "visible" just after a new request.

Here is an example response from the server:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=value
Set-Cookie: name2=value2; Expires=Wed, 09-Jun-2021 10:18:14 GMT

(content of page)

When you reload the page, your browser sends this:

GET / HTTP/1.1
Host: www.example.org
Cookie: name=value; name2=value2
Accept: */*

This is why the server can see them only after a new request by the browser.




回答2:


You are correct in assuming that cookies are not available until the next page load. Cookies are stored in the browser and created after the document is sent to the client. When the client loads (or reloads) any of your pages again, any existing cookies will be sent to the server along with the page request.




回答3:


Yes, cookies can only be access on subsequent page loads because the $_COOKIE global is populated before you set the cookie.

EDIT: See https://stackoverflow.com/a/7455234/996876




回答4:


The client (browser) sees the new cookie in the response to some request. It then sends it in all subsequent requests to the server. So yes, this is normal behaviour.



来源:https://stackoverflow.com/questions/13707721/are-newly-created-cookies-not-available-until-a-subsequent-page-load

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