PHP – setcookie() 不起作用

PHP – setcookie() not working(PHP – setcookie() 不起作用)
本文介绍了PHP – setcookie() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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 超全局变量在脚本启动时填充,然后在脚本的整个生命周期内不再被 PHP 修改或触及.这意味着 $_COOKIE 表示在启动脚本的 http 请求中发送到服务器的 cookie.它不会显示您在脚本生命周期中添加/更改/删除的任何 cookie.这些更改只会显示在 NEXT 请求中.

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.

唯一的例外是 $_SESSION,它在您调用 session_start() 时填充.

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

如果您需要立即将这些值添加到 $_COOKIE 中,则必须手动添加它们,例如

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() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to make 5 random numbers with sum of 100(如何制作5个总和为100的随机数)
str_shuffle and randomness(str_shuffle 和随机性)
Algorithm for generating a random number(生成随机数的算法)
What#39;s the disadvantage of mt_rand?(mt_rand 的缺点是什么?)
What is the best way to generate a random key within PHP?(在 PHP 中生成随机密钥的最佳方法是什么?)
How to create a random string using PHP?(如何使用 PHP 创建随机字符串?)