当我第一次创建cookie时,我似乎无法在后续页面加载之前获取相同的cookie。就好像cookie在浏览器中不存在,直到第二次请求页面为止。
我正在使用Kohana PHP框架:
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.
所以,我被引导相信这是正常的行为,我可能不明白cookie是如何工作的。谁能为我澄清这个?
答案 0 :(得分:9)
Cookie在HTTP标头中设置,因此当服务器返回页面时。 当您重新加载页面时,您的浏览器会将它们发送回服务器。
因此,在新请求之后,它们“可见”是完全正常的。
以下是来自服务器的示例响应:
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)
当您重新加载页面时,您的浏览器会发送以下信息:
GET / HTTP/1.1
Host: www.example.org
Cookie: name=value; name2=value2
Accept: */*
这就是服务器只有在浏览器发出新请求后才能看到它们的原因。
答案 1 :(得分:2)
您认为在下一页加载之前无法使用Cookie是正确的。 Cookie存储在浏览器中,并在将文档发送到客户端后创建。当客户端再次加载(或重新加载)您的任何页面时,任何现有的cookie都将与页面请求一起发送到服务器。
答案 2 :(得分:1)
是的,cookie只能在后续页面加载时访问,因为在设置cookie之前会填充$ _COOKIE全局。
答案 3 :(得分:0)
客户端(浏览器)在响应某个请求时看到新的cookie。然后它将所有后续请求发送到服务器。所以是的,这是正常行为。
答案 4 :(得分:0)
如果要在第一个php页面加载中使用cookie(用JS更改了值),则必须在php代码的顶部使用setcookie。 然后创建cookie,并可以在JS中更改其值,并在第一次php页面加载中使用。
示例:
<?php
setcookie('testCookie', 'testValue', 0, "/");
?>
<script type="javascript">
document.cookie = "testCookie=123456;path=/";
</script>
<?php
echo $_COOKIE['testCookie'];// return 123456
?>
在此示例中,如果您未在PHP代码顶部使用setcookie,则在第一页加载$ _COOKIE ['TestCookie']返回null。 表示php无法达到在javascript中更改的cookie值(在第一页加载中)。 此问题在第二页加载中不存在。