Search code examples
phppdobindparam

Using password_hash with bindParam


I'm trying to create a login system using Slim Jquery and Ajax. I've got the log in part working with minimal issues, now I just need to be able to hash the password. I know I can use md5, sha1 and/or salt to hash but I know that it is recommenced that password_hash is used instead. I know how to hash with any of the other 3 I mentioned because while using bindParam you can just place it around the variable. My question is, how do I use password_hash with bindParam. The closest answer I found on this site didn't do much to help.

My current code is:

$app->post('/addUser/', 'addUser');
function addUser()
{
    $request = \Slim\Slim::getInstance()->request();
    $q = json_decode($request->getBody());

    $sql = "INSERT INTO users(firstName, lastName, userName, password) VALUES (:firstName, :lastName, :userName, :password)";

    try{
        $dbConnection();
        $stmt=$db->prepare($sql);
        $stmt->bindParam("firstName", $q->firstName);
        $stmt->bindParam("lastName", $q->lastName);
        $stmt->bindParam("userName", $q->userName);
        $stmt->bindParam("password", $q->password);
        $stmt->execute();
        $db=null;
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
}

Verify Code:

$app->post('/logIn/', 'lonIn');
function logIn()
{
    $request = \Slim\Slim::getInstance()->request();
    $q = json_decode($request->getBody());

    $sql = "SELECT * FROM users WHERE userName=:userName";
    try{
        $db = getConnection();
        $stmt=$db->prepare($sql);
        $stmt->bindParam("userName", $q->userName);
        $execute = $stmt->execute();
        $db = null;
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
    if($execute == true)
    {
        $array = $stmt->fetch(PDO::FETCH_ASSOC);
        $hashedPassword = $array['password'];
        if(password_verify($q->password), $hashedPassword))
        {
            echo 'Valid';
        }
        else
        {
            echo 'Invalid';
        }
    }
}

Any help would be appreciated.


Solution

  • To encrypt password you need to create a new variable $hashedPassword which you will store in the db for each user. When verifying the user you will select a user from the db passing their username and using password_verify($passToBeVerified,$ourHashedpasswordfromDb) this will return a boolean.

          $app->post('/addUser/', 'addUser');
    
    function addUser() {
        $request = \Slim\Slim::getInstance()->request();
        $q = json_decode($request->getBody());
        $hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
    
        $sql = "INSERT INTO users(firstName, lastName, userName, password) VALUES (:firstName, :lastName, :userName, :password)";
    
        try {
            $dbConnection();
            $stmt = $db->prepare($sql);
            $stmt->bindParam(":firstName", $q->firstName);
            $stmt->bindParam(":lastName", $q->lastName);
            $stmt->bindParam(":userName", $q->userName);
            $stmt->bindParam(":password", $hashedPassword);
            $execute = $stmt->execute();
            if ($execute == true) {
                $verifyUser = verifyUser($q->password, $q->userName);
                if ($verifyUser == TRUE) {
                    echo 'valid Username and  Password';
                } else {
                    echo 'Invalid Username and password';
                }
            }
            $db = null;
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }
    
    function verifyUser($passWordToVerify, $userNameToVerify) {
        // $request = \Slim\Slim::getInstance()->request();
        //   $q = json_decode($request->getBody());
        //Select a user data according to their username
        $sql = "select firstName, lastName, userName, password from users where userName = :userName";
        try {
            $dbConnection();
            $stmt = $db->prepare($sql);
            $stmt->bindParam(":userName", $userNameToVerify);
            $execute = $stmt->execute();
            $db = null;
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
        if ($execute == True) {
            /*
             * if the query executes and returs the user saved user details lets now compare
             * the password from the db and the password that the user has entered
             */
            $array = $stmt->fetch(PDO::FETCH_ASSOC);
            $hashedPassword = $array['password'];
            if (password_verify($passWordToVerify, $hashedPassword)) {
                echo 'Password is valid!';
                return true;
            } else {
                echo 'Invalid password.';
                return false;
            }
        }
    }