php setcookie在php5下失败了

时间:2010-02-08 19:32:13

标签: php setcookie

我创建了这个简单的脚本,它将设置一个包含三个值的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>";
?>

4 个答案:

答案 0 :(得分:2)

您必须在输出到浏览器之前设置cookie。尝试移动echo电话下方的所有setcookie行。你可以这样做:

<?php
$set = false;
if (!isset($_COOKIE['taeinv'])) {
    $set = true;
    $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);

}
echo "<!DOCTYPE html>";
echo "<body>";
if ($set) {
    echo "No cookie set...   Attempted to set a new cookie.";
}
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>";
?>

答案 1 :(得分:0)

这适用于我的旧PHP4服务器,但不适用于PHP5。

答案 2 :(得分:0)

使用输出缓冲 - ob_start()ob_end_flush()

示例:

<?php
    ob_start();
    echo '<p>Initializing…</p>';
    setcookie('myLanguage', 'PHP');
    ob_end_flush();
    // you can continue your PHP code here…
?>

答案 3 :(得分:0)

我遇到了类似的问题,但只有在Chrome中,Cookie才会消失。 Firefox很好。

设置setcookie函数中的所有参数修复它。

这会设置Cookie,但Chrome会在点击内删除Cookie:

setcookie('uname', 'Joe', time()+3600*24);

这会设置cookie,浏览器会保留它:

setcookie('uname', 'Joe', time()+3600*24, '/', 'www.domain.com', false, false);