当登录成功时,我试图将用户重定向到另一个页面,$_SESSION[ 'logged_in' ] = true;
然而,当前的代码似乎不适合任何工作,逻辑上一切似乎都没问题。我是相当新的php大约两个星期,所以显然我错过了一些东西。我一直在四处寻找,看看我做错了什么,但仍然不能弄清楚,所以我在这里发帖作为最后的手段。谢谢你花时间看我的问题。
<?php
session_start();
//I have this on every single page.
include ( 'PasswordHash.php' );
//I use this for password hashing
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<form name="login" action="login.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<button type="submit">Login</button>
</form>
<?php
$username = $_POST[ 'username' ];
//take username from form
//start connection to database
$user = 'xxxx';
$pass = 'xxxx';
$db = new PDO( 'mysql:host=localhost;dbname=mydatabase', $user, $pass );
//establish a connection to the database
$sql = "SELECT * FROM users WHERE username=:username";
//select from table users only where the username matches username entered
$query = $db->prepare( $sql );
$query->execute( array( ':username'=>$username ) );
$results = $query->fetch( PDO::FETCH_OBJ );
//fetch object in that table
$stored_hash = $results->password;
//fetch only password column, this is the hash (used with PHpass)
$password = $_POST[ 'password' ];
//take password entered in form
$hash_obj = new PasswordHash( 8, false );
$check = $hash_obj->CheckPassword( $password, $stored_hash );
//check the password entered with CheckPassword class in PHpass
// HERE IS WHERE I GET LOST
if ( $check ){ //check if password matches hash
print_r( "This is a valid user" );
$_SESSION[ 'logged_in' ] = true; //current session is true
} else {
print_r( "Authentication failed, please Try again.");
$_SESSION[ 'logged_in' ] = false;
//current session is false
}
?>
<?php
if ( $_SESSION[ 'logged_in' ] == true ){ //okay session is true
header("Location:http://mywebsite/anotherpage.php");
//this is supposed to redirect to anotherpage.php
}else {
echo "You are not logged in<br/>";
//if not successfully logged in, echo this message
}
?>
</div>
这里是我的anotherpage.php:
<?php
session_start();
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<?php
if ( $_SESSION[ 'logged_in' ] == true ){
echo "You are logged in<br/>";
}else {
echo "You are not logged in<br/>";
}
?>
</div>
</body>
</html>
您在重定向之前发送了带有头的输出,要么使用输出缓冲,要么在向客户端发送任何内容之前进行重定向
如Limiter所说
在使用 之前,我需要使用输出缓冲来停止任何打印/回显。header("Location:/login_check.php");
我所做的是在session_start()
之后启动ob_start()
,在
ob_end_flush()
if ( $_SESSION[ 'logged_in' ] == true ){ //okay session is true
header("Location:http://mywebsite/anotherpage.php");
}else {
echo "You are not logged in<br/>";
}
//enter ob_end_flush() here