Password_verify in PHP

早过忘川 提交于 2019-12-08 13:32:07

问题


So I'm enabling users to create accounts with a username and password. I have managed to encrypt the password when a user creates a new account using:

$hash = password_hash($password, PASSWORD_BCRYPT);

However I'm having trouble with password_verify when logging in, could someone please help me with what I have? I know it's something like this:

password_verify($password, $hash)

But I don't know how to structure it or where to add it in the code. Thanks in advance. This is what I have:

<?php
if (isset($_GET["username"])  && isset($_GET["password"]) ){
    $username = $_GET["username"];
    $password = $_GET["password"];
    $result = login( $username, $password);
    echo $result;
}

function makeSqlConnection()
{
    $DB_HostName = "";
    $DB_Name = "";
    $DB_User = "";
    $DB_Pass = "";

    $con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); 

    mysql_select_db($DB_Name,$con) or die(mysql_error()); 

    return $con;
}

function disconnectSqlConnection($con)
{
    mysql_close($con);
}

function login($username, $password)
{
    $con = makeSqlConnection();
    $sql = "select * from login  where username = '$username' and password = '$password';";
    $res = mysql_query($sql,$con) or die(mysql_error());

    $res1 = mysql_num_rows($res);

    disconnectSqlConnection($con);

     if ($res1 != 0) {
        return 1;
    }else{
        return 0;
    }// end else

}// end of Function 
?>

回答1:


The general practice is as follows:

  1. Fetch password hash from the database where the username = the inputted username.
  2. If rows are found, then there's a user
  3. Now you compare the inputted password against the hash stored in the database.

I'll outline the above flow in some pseudo code for you here:

$query = SELECT password FROM users WHERE username = '$username'

$data = FETCH_THE_DATA($query);

if(password_verify($USER_INPUTTED_PASSWORD, $data['password'])) {
    // password is correct
} else {
    // password is in-correct
}

Notes

  • Stop using mysql_* functions. The library is deprecated as it's unreliable and will be removed in future releases of PHP.
    • You're better off using PDO or MySQLi Prepared Statements
  • You should always read the manual - password_verify(), it states clearly that you compare the "user inputted password" against the hashed version which is stored in your database.



回答2:


Since I'm feeling good and sleepy today, I'll write a bunch of codes.

This is an example how to use PDO with prepared statement. You will have to tweak it according to your needs and you have to check if the post/get not empty as well. I prefer to use POST request for login so this example will use POST request..

This is my user class. Which use placeholders and binding instead of passing the parameters into the query directly. This will give some protections against SQL injection attack.

class User{

    private $dbh;


    function __construct(){

        $this->dbh = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME.';charset=utf8mb4', DB_USER, DB_PASSWORD) or die('db connect error');
    }


    function create($username, $password){

        $status = false;

        try{

            $stmt = "INSERT INTO login (username, password)
                        VALUES (?, ?)";

            $qry = $this->dbh->prepare($stmt);

            $qry->bindParam(1, $username);
            $qry->bindParam(2, $password);

            $status = $qry->execute();
        }catch(PDOException $e){

            $e->getMessage();
        }

        $qry->closeCursor();

        return $status;        

    }

    public function getPassword($username){

        $status = false;
        try{
            $stmt = "SELECT * FROM login WHERE username = ? LIMIT 1";

            $qry = $this->dbh->prepare($stmt);
            $qry->bindParam(1, $username);
            $qry->execute();

            $status = $qry->fetch(PDO::FETCH_ASSOC);
        }catch(PDOException $e){

            $e->getMessage();
        }
        $qry->closeCursor();

        return $status;
    }    

}

This is how to create the user. Note that I don't check if the username already exist. You can either implement it yourself or use unique index on username column provided that the collation is case insensitive. I have also increased the cost from the default that is 10 and I defined PASSWORD_DEFAULT to be used because I want the PHP engine to always use the strongest available algorithm (currently bcrypt).

function hashPassword($password){

            $password = password_hash($password, PASSWORD_DEFAULT,array('cost' => 16));
            return $password;
}

$user = new User;
$_POST['password'] = hashPassword($_POST['password']);


if(!$user->create(trim($_POST['username']),$_POST['password'])){

    echo 'Failed creating user';
}else{
    echo 'User created';
}

This is how to verify the password.

$user = new User;
$getPassword = $user->getPassword(trim($_POST['username']));

if(!$getPassword){

    echo 'Error fetching user';
}else{

    if(!password_verify($_POST['password'], $getPassword['password'])){

        echo 'Login failed';
    }else{

        echo 'Login successful';        
    }
}


来源:https://stackoverflow.com/questions/31664812/password-verify-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!