I have successfully used Phpass to hash registered users passwords and store them in a database, now i am stuck on the login how to check the sumbitted username and password, checking the username exists in the database then checking the hashed password against the one given.
Any help much appreciated!!! Thankyou!
This is my code:
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
require("PasswordHash.php");
$hasher = new PasswordHash(8, false);
$username = $_POST['username'];
$password = $_POST['password'];
// Passwords should never be longer than 72 characters to prevent DoS attacks
if (strlen($password) > 72) { die("Password must be 72 characters or less"); }
$query = "SELECT * FROM user WHERE username = '$username'";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows = 1) {
$res = mysql_query("SELECT password FROM user WHERE username = '$username'");
$row = mysql_fetch_array($res);
$hash = $row['password'];
$password = $_POST['password'];
if ($hasher->CheckPassword($password, $hash)) { //$hash is the hash retrieved from the DB
$what = 'Authentication succeeded';
} else {
$what = 'Authentication failed';
}
} else {
echo "No Such User";
include 'login.php';
exit();
}
echo "$what\n";
echo "<br />";
echo "$hash";
?>
THIS IS MY WORKING CODE FOR BENEFIT OF OTHERS:
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
require("PasswordHash.php");
$hasher = new PasswordHash(8, false);
$username = $_POST['username'];
$password = $_POST['password'];
// Passwords should never be longer than 72 characters to prevent DoS attacks
if (strlen($password) > 72) { die("Password must be 72 characters or less"); }
$query = "SELECT * FROM user WHERE username = '$username'";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows = 1) {
$res = mysql_query("SELECT * FROM user WHERE username = '$username'");
$row = mysql_fetch_array($res);
$hash = $row['password'];
$password = $_POST['password'];
if ($hasher->CheckPassword($password, $hash)) { //$hash is the hash retrieved from the DB
$what = 'Authentication succeeded';
} else {
$what = 'Authentication failed';
}
} else {
echo "No Such User";
include 'login.php';
exit();
}
echo "$what\n";
echo "<br />";
echo "$hash";
?>
Here's how phpass works: When you save the user's password (when they create it) you hash it before saving, like so:
Then save
$hash_value
in the database as the user's password. When you go to validate the user, look up the user by username. If found, compare the actual password from the database (stored hash) with a hash of what the user entered:Make sure to initialize the
PasswordHash
class the same way each time, with the same values for$hash_iterations
and$portable_hashes
, or the comparison won't work correctly.