Aamir
Aamir

Reputation: 2283

How to use php's password_hash() method..?

I'm getting password does not match when I login, when a user signup, I'm saving password as

$password = password_hash($this->input->post('password'), PASSWORD_BCRYPT);

when a user login I'm checking password like this,

    $hash = password_hash($password, PASSWORD_BCRYPT);
    $this->db->select('password');
    $this->db->from('usersdetails');
    $this->db->where('email', $email);
    $this->db->limit(1);
    $query = $this->db->get();
    $passwordcheck = $query->row()->password;
    if (password_verify($passwordcheck, $hash)) {
       return true;
    } else {
        return false;
    }

BUT it always return password does not match..why????? Any help is much appreciated...

Upvotes: 0

Views: 1302

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94672

You are supposed to check the raw unhashed password, as the password_verify() does the re-hashing of the raw password using the hash routine used when creating the hashed password.

If you look at the result of the password_hash() there is information stored in the hash about which hash routine was used to create this hash, and how it was generated

$password = 'FredsTheMan';

$hash = password_hash($password, PASSWORD_BCRYPT);

if (password_verify($password, $hash)) { 
   return true;
} else {
    return false;
}

Another common mistake in this area is not giving the column you use on the database table enough characters to hold the full result of the hash

The hash generated using PASSWORD_BCRYPT is 60 characters

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Beware, when other hashes are providied in the furure, they may result in a hash longer than 60 characters

So in short you code should be

$this->db->select('password');
$this->db->from('usersdetails');
$this->db->where('email', $email);
$this->db->limit(1);
$query = $this->db->get();
$pwd_from_db = $query->row()->password;

if (password_verify($this->input->post('password'), $pwd_from_db)) {
   return true;
} else {
    return false;
}

Upvotes: 5

Related Questions