Can anyone tell me why I keep returning FALSE even if I put in the right value?
before executing this code, put the password into the database. $encrypted_pw = password_hash ($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);
}
?>
>
As pointed out you were missing the benefit of using a prepared statement by directly embedding unsanitised user input in your sql query - use a placeholder in the sql and bind your input data to that.
<?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));
}
?>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments