screencast screencast -4 years ago 65
PHP Question

How to check a login password against a hashed password in PHP

Does anyone have a generic method/function for checking a login password against a hashed password in a database?
I've seen some examples but it's not clear how they are meant to work in practice i.e.:
"To check if password $pass (from user login form usually) fits the database saved hash $hash."

password_verify($pass, $hash)

Is this $hash pulled from the database and if so what is the method for accomplishing this?
Any help advice is appreciated.

I've tried using this login function: someone suggested I use Hash::check but this throws a fatal error on undefined function.

public function login($username = null, $password = null) {
$user=$this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)){

}
}
}

Answer Source

You need to first check the email of the user and then match the password against it.

function login($email,$password){
    global $connection;
    $query = "SELECT * FROM table_name WHERE email = '$email'";

    $result_set=mysqli_query($connection,$query);
        if (mysqli_num_rows($result_set) === 1) {
            $row = mysqli_fetch_assoc($result_set);
            if (password_verify($password, $row['password'])) {
                $_SESSION['user_id'] = $row['id'];
                redirect_to("welcome.php");
            }else{
                echo " <script>alert('Password is incorrect');</script>  ";
            }
        }else{
            echo " <script>alert('No email found: {$email}');</script>  ";
        }


}

$email = mysqli_real_escape_string (  $connection,  $_POST['email']);
$password= mysqli_real_escape_string (  $connection,  $_POST['password']);
login($email,$password);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download