我有三个页面:
- 索引.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');
?>