PHP - setcookie()不工作 [英] PHP – setcookie() not working

查看:118
本文介绍了PHP - setcookie()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个页面设置一个cookie,并回到一个字符串,如果你选中一个复选框。字符串打印正确,但cookie从未设置,我不知道为什么。

 < form action =< ?php echo $ _SERVER ['PHP_SELF']?> method =post> 
< label for =checkbox>选项1:< / label>
< input type =checkboxname =checkboxid =checkbox>< br>
< input type =submitname =submitvalue =Submit>
< / form>
<?php
if(isset($ _ POST ['checkbox'])){
setcookie(cookie,on,time()+ 3600 * 24);
echo您选中了复选框,并且Cookie的值设置为:< br>;
}
else {
setcookie(cookie,off,time()+ 3600 * 24);
echo您没有选中复选框,并且Cookie的值设置为:< br>;
}
echo $ _COOKIE ['cookie'];
?>

有人知道上述代码为什么不起作用吗?

$ _ COOKIE 表示在发出脚本的http请求中发送到服务器的Cookie。它不会显示您在脚本生命周期中添加/更改/删除的任何Cookie。这些更改只会显示在NEXT请求中。



唯一的例外是 $ _ SESSION 当你调用 session_start()时填充。



如果你需要这些值立即在$ _COOKIE,必须手动添加,例如

  setcookie('cookie',$ value,....); 
$ _COOKIE ['cookie'] = $ value;


I have this page that sets a cookie and echos out a string if you check a checkbox. The string prints correctly, but the cookie never gets set and I have no idea why.

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label for="checkbox">Option 1:</label>
<input type="checkbox" name="checkbox" id="checkbox"><br>
<input type="submit" name="submit" value="Submit">
</form>
  <?php
if (isset($_POST['checkbox'])) {
  setcookie("cookie", "on", time()+3600*24);
  echo "You checked the checkbox and a cookie was set with a value of:<br>";
}
else {
  setcookie("cookie", "off", time()+3600*24);
  echo "You didn't check the checkbox and a cookie was set with a value of:<br>";
}
echo $_COOKIE['cookie'];
  ?>

Does anyone know why the above code does not work?

解决方案

PHP superglobals are populated at script start-up time, and then are NOT modified or touched by PHP again for the life of the script. That means $_COOKIE represents the cookies that were sent to the server in the http request that fired up the script. It will NOT show any cookies you've added/changed/deleted during the life of the script. Those changes will only show up on the NEXT request.

The only exception to this is $_SESSION, which is populated when you call session_start().

If you need those values to be in $_COOKIE immediately, you'll have to add them manually, e.g.

setcookie('cookie', $value, ....);
$_COOKIE['cookie'] = $value;

这篇关于PHP - setcookie()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆