素材牛VIP会员
PHP cookie读取报错,上代码
 铁***1  分类:ThinkPHP  人气:1074  回帖:2  发布于6年前 收藏

<?php

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


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

echo $_COOKIE['name'];

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

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv6 码匠
su***in 技术总监 6年前#1

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

Set-Cookie: PHPSESSID=tbmh6ussjmqrblhth75qb9h2l0; path=/

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

Cookie: PHPSESSID=tbmh6ussjmqrblhth75qb9h2l0

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

they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS 
Lv2 入门
雨***3 页面重构设计 6年前#2
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS 

php对setcookie函数的说明。

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取