I'm trying to check users hashed passwords against the ones I've saved in the database. It is almost the same issue as the this guy, but I'm trying to do it with PDO and I'm unsure how to get the hashed password from the database to check it against. Here is my code for the login page so far:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once "/home/carlton/public_html/PHPproject/includes/PasswordHash.php";
if ($_POST){
$form = $_POST;
$username = $form['username'];
$password = $form['password'];
try{
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PODException $e){
echo "Can't connect to the database";
}
$sql = "SELECT * FROM users WHERE username=:username";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$username, ':password'=>$stored_hash));
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$check = $hash_obj->CheckPassword($password, $stored_hash);
if($check){
print_r("Registered user");
}
else{
print_r("Not a registered user");
}
//login here
}
else{
?>
<form name="login" action="login.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<button type="submit">Submit</button>
<button type="reset">Reset Form</button>
</form>
<?php
}
?>
Pseudocode:
$q=$db->prepare('SELECT * FROM usertable WHERE username=? AND passwordhash=?');
$thehashvalue=calc_hash_of_password_according_to_your_agorithm($params);
$theusername=the_username_that_was_posted();
$q->execute(array($theusername, $thehashvalue));
$lastlogin=null;
while($r=$q->fetch(PDO::FETCH_ASSOC)) {
# successfully authenticated
$lastlogin=$r['lastlogin']; ## example. assumes a "lastlogin" column on "usertable"
}
if(!empty($lastlogin)) {
# user is logged in
}else{
# login failed
}
The hash calc function could be as simple as md5($posted_passwd)
but it is good practise to salt the hash so the same password makes different hashes for different users and/or on different systems. Just make sure you use the same hash function when storing the password hash in the database.