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

时间:2013-02-06 07:49:12

标签: php cookies

我有三页:

  • index.php,
  • login.php和
  • logout.php。

如果您尚未登录,索引页面会将您重定向到登录页面。当您登录时,它会将您重定向到索引页面,您可以在其中注销。一切都很顺利。但这是奇怪的事情,在我看来它不应该。

据我所知。 Header,setcookie和session语句只能在之前使用 将任何输出发送到浏览器,但如果您查看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');
?>

1 个答案:

答案 0 :(得分:0)

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

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

查看标头是否已发送?

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