Reputation: 167
I am currently experimenting with the password_hash() and password_verify() method..
So I tought I go ahead and create a little login/register with it.
The problem is whenever I open the login the output is:
failed
And I have no clue why.. I already set the length of the password field in my database to 255 but it is still not working.
This is my register.php:
<?php
require_once('db.php');
$username = mysqli_real_escape_string($db, $_GET['username']);
$password = mysqli_real_escape_string($db, $_GET['password']);
$p = password_hash($_GET['password'], PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->bind_param('ss', $username, $p);
$stmt->execute();
$stmt->close();
$db->close();
?>
And my login looks like this:
<?php
session_start();
error_reporting(0);
require_once('db.php');
function e($input) {
return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
}
$username = mysqli_real_escape_string($db, $_GET['username']);
$password = mysqli_real_escape_string($db, $_GET['password']);
$stmt = $db->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$row = $stmt->fetch();
if (!empty($row)) {
if (password_verify($_GET['password'], $row['password'])) {
echo 'success';
}
else
{
echo 'failed';
}
}
else
{
echo "This user does not exist";
}
$stmt->close();
$db->close();
?>
I don't know how to get this working :/
Upvotes: 1
Views: 442
Reputation: 54796
$stmt->fetch();
does not return data. It binds data to variables defined in bind_result()
.
So after $stmt->fetch()
you will have username in $username
and password in $password
.
So, what really should be compared is:
if ($stmt->fetch()) {
// here
if (password_verify($_GET['password'], $password)) {
echo 'success';
}
else
{
echo 'failed';
}
}
else
{
echo "This user does not exist";
}
Upvotes: 5