为什么我只能在刷新页面后才能使用cookie


Why do i can use cookies only after I refreshed the page?

我运行了这个简单的例子,但我看到的是"Undefined index:color",而不是预期的"red"。但刷新页面后,我看到"红色"。那么我的错误是什么呢?谢谢

<?php
setcookie("color","red");
echo $_COOKIE["color"];
?>

原因是您的setcookie函数没有将值放入$_COOKIE中。

在刷新期间(当发出新的HTTP请求时),$_COOKIE将加载所有更新的值,因此您可以看到它。