0

我有三个页面:

  • 索引.php,
  • login.php 和
  • 注销.php。

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

我所知道的。Header、setcookie 和 session 语句只能在向浏览器发送任何输出之前使用,但如果您查看 login.php 页面,它已经发送了 HTML 代码。为什么这不起作用?我在这里想念什么?

索引.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');
    }
?>

登录.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>

注销.php:

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

1 回答 1

0

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

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

看看标头是否已经发送?

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

于 2013-02-06T08:14:58.590 回答