2013-02-06 49 views
0

我有三個頁面:cookie被髮送

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

如果您未登錄,索引頁會將您重定向到登錄頁面。登錄後,它會將您重定向到索引頁面,您可以在其中登出。而且一切都很好。但那是奇怪的事情,在我看來它不應該。

據我所知。標題,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'); 
?> 
+2

您可能在您的php配置中啓用了output_buffering。意思是在php腳本結束之前實際上沒有輸出。 – Supericy

+0

也許它不發送HTML,只是重定向到正確的頁面? – Gntem

+0

錯誤代碼,使用'$ _SESSION'而不是Cookie。 –

回答