PHP password_hash(), password_verify()

你离开我真会死。 提交于 2019-11-26 14:44:57
Funk Forty Niner

Here is what I use for password_hash and password_verify. Try it out as written, you can then start adding in the rest of your code once successful.

Modify table and column name(s) to suit.

N.B.: This is a basic insertion method. I suggest you use prepared statements instead.

Sidenote: The password column needs to be long enough to accomodate the hash VARCHAR(255). Consult "Footnotes".

INSERT file

<?php
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';

$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}

$password = "rasmuslerdorf";
$first_name = "john";
$password = password_hash($password, PASSWORD_DEFAULT);

$sql = "INSERT INTO users (`name`, `password`) VALUES ('" .$first_name ."', '" .$password ."')";

    $query = mysqli_query($conn, $sql);
    if($query)

{
    echo "Success!";
}

else{
    // echo "Error";
    die('There was an error running the query [' . $conn->error . ']');
}

LOGIN file

<?php
// session_start();

$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';

$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
  die('Connection failed [' . $conn->connect_error . ']');
}

$pwd = "rasmuslerdorf";
$first_name = "john";

//$sql = "SELECT * FROM users WHERE id = 1";

        $sql = "SELECT * FROM users WHERE name='$first_name'";
        $result = $conn->query($sql);
        if ($result->num_rows === 1) {
            $row = $result->fetch_array(MYSQLI_ASSOC);
            if (password_verify($pwd, $row['password'])) {

                //Password matches, so create the session
                // $_SESSION['user'] = $row['user_id'];
                // header("Location: http://www.example.com/logged_in.php");

                echo "Match";

            }else{
                echo  "The username or password do not match";
            }

}

 mysqli_close($conn);

Footnotes:

The password column should be long enough to hold the hash. 72 long is what the hash produces in character length, yet the manual suggests 255.

Reference:

"Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice)."

Friends as we are using Unique Username for Login, So we have to Fetch Password/Data from Database using Username Only.

Example:

<?php
    $connect = mysqli_connect($localhost, $username, $pwd, $database) or die("Opps some thing went wrong");

    if (isset($_POST['submit'])) {
      extract($_POST);

     // Get Old Password from Database which is having unique userName
     $sqlQuery = mysqli_query($connect, "select * from loginTable where User='$username'");
     $res = mysqli_fetch_array($sqlQuery);
     $current_password = $res['userPassword'];

     if (password_verify($enteredPassword, $current_password)) { 
        /* If Password is valid!! */
        $_SESSION['id'] = $res['id'];
        header("location: home.php");
     }
     else { 
        /* If Invalid password Entered */
        $alt = "Login Failed! Wrong user ID or Password";
        header("location: index.php?m=$alt");
     }
  }
?>

It is Working for me... I am fetching Password from database and comparing with entered Password Using PHP API i.e. password_verify($enteredPassword, $current_password)

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