任何人都可以告诉我为什么即使我输入正确的值也要返回FALSE吗?
在执行此代码之前,将密码放入数据库。$ encrypted_pw =密码哈希($ user_pw,PASSWORD_DEFAULT);
<?php
//From Android to php
$user_id = $_POST["user_id"];
$user_pw = $_POST["user_pw"];
$statement = mysqli_prepare($con, "SELECT user_pw FROM USER WHERE user_id = $user_id");
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
//USERDB contains the password that has already been hashed.
$response = array();
if(password_verify($user_pw, $statement)) {
$response["success"] = true;
$response["user_id"] = $user_id;
$response["user_pw"] = $user_pw;
echo json_encode($response);
} else {
$response["success"] = false;
echo json_encode($response);
}
?>
>
正如所指出的那样,通过将未过滤的用户输入直接嵌入到SQL查询中,您失去了使用预准备语句的好处-在sql中使用占位符并将输入数据绑定到该占位符。
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST["user_id"], $_POST["user_pw"] ) ){
# use a placeholder in the sql for the user supplied data
$sql='select `user_pw` from `user` where `user_id`=?';
# attempt to create the prepared statement
$stmt=$con->prepare( $sql );
$response=[
'success' => false,
'user_id' => false,
'user_pw' => false
];
if( $stmt ){
# bind the user data to the placeholder & execute the query
$stmt->bind_param( 's', $_POST["user_id"] );
$res=$stmt->execute();
# process the result & bind new variables to each field in recordset
if( $res ){
$stmt->store_result();
$stmt->bind_result( $pwd );
$stmt->fetch();
# check the supplied password against hash from db
$status=password_verify( $_POST["user_pw"], $pwd );
if( $status ){
$response=[
'success' => $status,
'user_id' => $_POST["user_id"],
'user_pw' => $_POST["user_pw"]
];
}
$stmt->free_result();
$stmt->close();
}
}else{
exit('Failed to create sql statement');
}
exit(json_encode($response));
}
?>