Home > Backend Development > PHP Tutorial > thinkPHP cookie读取报错,上代码

thinkPHP cookie读取报错,上代码

WBOY
Release: 2016-06-06 20:34:36
Original
1534 people have browsed it

<code>setcookie('name',234,time()+10,'/');


//$b = $_COOKIE['name'];

echo $_COOKIE['name'];
</code>
Copy after login
Copy after login

为什么这个代码,第一次执行的时候报错,会报
Notice: Undefined index: name in D:\wamp\Apache\htdocs\test.php on line 10
未定义的索引 name ,我明明是先设置了COOKIE 再读取的啊?求详细解释

回复内容:

<code>setcookie('name',234,time()+10,'/');


//$b = $_COOKIE['name'];

echo $_COOKIE['name'];
</code>
Copy after login
Copy after login

为什么这个代码,第一次执行的时候报错,会报
Notice: Undefined index: name in D:\wamp\Apache\htdocs\test.php on line 10
未定义的索引 name ,我明明是先设置了COOKIE 再读取的啊?求详细解释

cookie 设置不是立即生效的, setcookie() 只是在 response header 头里加上 Set-Cookie 头,例如:

<code>Set-Cookie: PHPSESSID=tbmh6ussjmqrblhth75qb9h2l0; path=/
</code>
Copy after login

这个响应到达客户端, Cookie 设置成功后, 下次 客户端的请求就会在 Header 里带上这个头:

<code>Cookie: PHPSESSID=tbmh6ussjmqrblhth75qb9h2l0
</code>
Copy after login

此时才能通过 $_COOKIE 取到这个值。这就是为什么:

<code>they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS 
</code>
Copy after login

<code>Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS 
</code>
Copy after login

php对setcookie函数的说明。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template