php setcookie 在 php5 下失败
我创建了这个简单的脚本,它将设置一个具有三个值的 cookie,或者检索 cookie 值(如果已设置)。在我的运行 PHP4 的服务器上,一切正常。在我的 PHP 5 (5.2.11) 服务器上,脚本无法在浏览器中设置 cookie。我已经检查过我的 php.ini 中是否启用了输出缓冲,并且确实如此。有谁知道为什么这不起作用?
<?php
echo "<!DOCTYPE html>";
echo "<body>";
if (!isset($_COOKIE['taeinv'])) {
echo "No cookie set... Attempting to set a new cookie.";
$user = "testuser";
$role = "admin";
$expire = "true";
$halfHour = 1800;
setcookie("websitename[Expire]", $expire, time()+$halfHour);
setcookie("websitename[User]", $user, time()+$halfHour);
setcookie("websitename[Role]", $role, time()+$halfHour);
}
if (isset($_COOKIE['websitename'])) {
echo "Cookie Values:";
echo "<br />";
foreach ($_COOKIE['websitename'] as $name => $value) {
echo "<b>$name</b> : $value <br />\n";
}
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>
I created this simple script which will either set a cookie with three values or retrieve the cookies values if they are already set. On my server running PHP4, everything works. On my server with PHP 5 (5.2.11), the script fails to set the cookie in the browser. I already checked if output buffering is enabled in my php.ini and it is. Does anyone have any ideas as to why this fails to work?
<?php
echo "<!DOCTYPE html>";
echo "<body>";
if (!isset($_COOKIE['taeinv'])) {
echo "No cookie set... Attempting to set a new cookie.";
$user = "testuser";
$role = "admin";
$expire = "true";
$halfHour = 1800;
setcookie("websitename[Expire]", $expire, time()+$halfHour);
setcookie("websitename[User]", $user, time()+$halfHour);
setcookie("websitename[Role]", $role, time()+$halfHour);
}
if (isset($_COOKIE['websitename'])) {
echo "Cookie Values:";
echo "<br />";
foreach ($_COOKIE['websitename'] as $name => $value) {
echo "<b>$name</b> : $value <br />\n";
}
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须在向浏览器输出任何内容之前设置 cookie。尝试将所有
echo
行移至setcookie
调用下方的某个位置。你可以这样做:You have to set the cookie before any output to the browser. Try moving all
echo
lines somewhere below thesetcookie
call. You could do something like this:这在我的旧 PHP4 服务器上有效,但在 PHP5 上无效。
That worked on my old PHP4 server, but not on PHP5.
使用输出缓冲 –
ob_start()
和ob_end_flush()
。示例:
Use output buffering –
ob_start()
andob_end_flush()
.Example:
我也遇到了类似的问题,但只有在 Chrome 中,cookies 才消失。火狐浏览器很好。
设置
setcookie
函数中的所有参数修复了该问题。这会设置 cookie,但 Chrome 会在一次点击中删除 cookie:
这会设置 cookie 并且浏览器会保留它:
I had a similar problem but it was only in Chrome that the cookies disappeared. Firefox was fine.
Setting all the parameters in the
setcookie
function fixed it.This sets the cookie but Chrome drops the cookie within a click:
This sets the cookie and the browser retains it: