当我尝试登录时,它不显示任何信息,也没有从数据库中获取数据。
if($_SERVER['REQUEST_METHOD']=='POST'){
//filter this variable for security
$username = strip_tags(mysqli_real_escape_string($conn, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($conn, trim($_POST['password'])));
$stmt = $conn->prepare("SELECT id FROM students WHERE s_id = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$user = $stmt->fetch();
if($user == FALSE) {
die("Incorrect");
}else {
$password_hash = $user['password'];
$validPassword = password_verify($password, $password_hash);
if($validPassword){
echo "success";
} else{
//$validPassword was FALSE. Passwords do not match.
echo 'Incorrect username / password combination!<br/>';
echo $user['password'];
}
}
}
答案 0 :(得分:0)
您的查询仅选择ID。更改查询以选择您的ID和密码。
$stmt = $conn->prepare("SELECT * FROM students WHERE s_id = ?");
然后,您将在结果中输入哈希密码$user['password']
。
答案 1 :(得分:0)
我很想将所有内容包装在try/catch
块中,并在关键点引发异常以确定代码在哪里中断。另外,我认为在使用$stmt->bind_result
在使用准备好的语句时,我建议您不要使用mysqli_real_escape_string
也不要使用trim
,因为密码以空格开头或结尾是完全有效的-数据库引擎将以安全的方式处理该语句。
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['username'],$_POST['password']) ){
try{
$args=array(
'username' => FILTER_SANITIZE_STRING,
'password' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
$stmt = $conn->prepare("select `password` from `students` where `s_id` = ?");
if( $stmt ){
$stmt->bind_param( "s", $username );
$result = $stmt->execute();
if( $result ){
/* There should be only 1 record - bind to a variable */
$stmt->bind_result( $pwdhash );
/* fetch the results of the query */
$stmt->fetch();
/* is the password correct? */
$validpassword = password_verify( $password, $pwdhash );
echo $validpassword ? 'Success' : 'Error: Incorrect username or password';
$stmt->close();
} else {
throw new Exception('No results returned');
}
} else {
throw new Exception('failed to prepare sql query');
}
} catch( Exception $e ){
exit( $e->getMessage() );
}
}