I am trying to use password hashing using phpmysql. The issue is password_verify does not seem to work for me so far. Say, my password during registration is '123456789'. I stored it in database using
password_hash('123456789', PASSWORD_BCRYPT, array('cost' => 12));
And then when I enter '123456789' in the login field, it does nothing, fails.
Here is my code:
<?php
session_start();
include('db.php');
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p/>
<?php
if(isset($_POST['login']) && $_POST['login'] == 'Login') {
$loginEmail = $_POST['loginEmail'];
$loginPassword = $_POST['loginPassword'];
$sqlLogin = $db->prepare("SELECT * FROM registered_users WHERE email = ?");
$sqlLogin->bind_param("s",$loginEmail);
$sqlLogin->execute();
$sqlLogin = $sqlLogin->get_result();
$numrowsLogin = $sqlLogin->num_rows;
if($numrowsLogin == 1) {
$rowLogin = $sqlLogin->fetch_assoc();
$stored_password = $rowLogin['password'];
}
if(password_verify($loginPassword, $stored_password)){
header('Location: homepage.php');
}else{
echo 'invalid login';
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<table style="width:500px">
<tr>
<td width="30%"><input style="width: 200px; height: 25px; border-radius: 5px;" type="text" name="loginEmail" placeholder = "Email" required/><br/></td>
</tr>
<tr>
<td width="30%"><input style="width: 200px; height: 25px; border-radius: 5px;" type="password" name="loginPassword" placeholder = "Password" required/><br/></td>
</tr>
</table>
<input style="font-weight: bold; width: 70px; height: 25px; border-radius: 5px;" type="submit" name="login" value="Login"/>
</form>
</body>
</html>
@Fred Li : thanks, that worked for me. My password column length in the database was 50. updated it and works now, thankyou once again!! – Bishwaroop Chakraborty"
As discussed in commments:
Example from http://php.net/manual/en/function.password-hash.php
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
is 60 chars.
Your password column's length is less than 60 and that's the problem.
It's too short and your code failed silently because of it and you need to start over with a new hash after altering the column's length.
- The manual says that 255 is a good bet.
Notes:
Pay attention to other comments left in regards to XSS injection.
Here are a few good articles:
- How to prevent XSS with HTML/PHP?
- https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
and to add exit;
after header. Otherwise, your code may want to continue to execute.
来源:https://stackoverflow.com/questions/38226156/password-hashing-not-working-in-php-mysql