发送任何其他输出之前使用的cookie


cookie used before any other output is sent

我有三个页面:

  • index.php
  • login.php和
  • logout.php

如果您没有登录,索引页会将您重定向到登录页。当您登录时,它会将您重新定向到索引页,您可以在那里注销。一切都很顺利。但这很奇怪,在我看来不应该。

据我所知。Header、setcookie和会话语句只能在将任何输出发送到浏览器,但如果您查看login.php页面,它已经发送了HTML代码。为什么不起作用?我在这里错过了什么?

index.php:

<?php
    if (isset ($_COOKIE['uid'])) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Index Page</title>
    </head>
    <body>
    Logged in with UID: <?php echo $_COOKIE['uid']; ?>
    <br/>
    <a href="logout.php">Log Out</a>
</body>
</html>
<?php
    } else {
        /* If no UID is in the cookie, we redirect to the login page */
        header('Location: http://localhost/cookie/login.php');
    }
?>

login.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Login</title>
    </head>
    <body>
<?php
    function check_auth() { 
        return 4; 
    }
    if (isset ($_POST['login']) &&  ($uid = check_auth($_POST['email'], $_POST['password'])))
    {
        /* User succesfully logged in, setting cookie */
        setcookie('uid', $uid, time() + 14400, '/');
        header('Location: http://localhost/cookie/index.php');
    } elseif (isset($_COOKIE['uid'])) {
        /* If try to  go to login.php when you already logged in, we redirect to the index page */
        header ('Location: http://localhost/cookie/index.php');
    } else {
?>
    <h1>Log-in</h1>
    <form method="post" action="login.php">
        <table>
        <tr><td>E-mail address:</td><td><input type='text' name='email'/></td></tr>
        <tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
        <tr><td colspan='2'><input type='submit' name='login' value='Log in'/></td></tr>
        </table>
    </form>
<?php
    }
?>
</body>
</html>

logout.php:

<?php
    setcookie('uid', '', time() - 86400, '/');
    header('Location: http://localhost/cookie/login.php');
?>

login.php文件中的header()函数确实很奇怪。标头应该已经发送,并且不应该工作。你为什么不试试

bool headers_sent ([ string &$file [, int &$line ]] )

查看标头是否已发送?

http://www.php.net/manual/en/function.headers-sent.php