pass in password_hash field with pdo

依然范特西╮ 提交于 2019-11-29 18:28:52

Its really quite simple once you read the manual or see an example in a tutorial. See comments in the code for details

<?php
include_once("config.php");
session_start();

if(isset($_POST['signup'])){
    $name = $_POST['name'];
    $email = $_POST['email'];

    // at signup you hash the user provided password
    $pass = password_hash($_POST['pass'], PASSWORD_DEFAULT);

    $insert = $pdo->prepare("INSERT INTO users (name,email,pass)
                                values(:name,:email,:pass) ");
    $insert->bindParam(':name',$name);
    $insert->bindParam(':email',$email);
    $insert->bindParam(':pass',$pass);   // this stores the hashed password
    $insert->execute();
}elseif(isset($_POST['signin'])){
    $email = $_POST['email'];
    $pass = $_POST['pass'];

    // as the password on the DB is hashed you cannot use the
    // plain text password in the SELECT here as it wont match
    $select = $pdo->prepare("SELECT * FROM users WHERE email=:email");

    // no idea what this was doing
    //$select->setFetchMode();
    $select->bindParam(':email',$email);
    $select->execute();

    $row = $select->fetch(PDO::FETCH_ASSOC);

    // verify the plain text password against the 
    // hashed value from DB in $row['pass']
    if( password_verify($pass, $row['pass']) ){
        $_SESSION['email'] = $data['email'];
        $_SESSION['name']  = $data['name'];
        header("location:profile.php"); 
        exit;
    } else {
        echo "invalid email or pass";
    }
}

And as to the length of the column in the database that you need to hold this hashed value, it is documented in the manual

The following algorithms are currently supported:

  • PASSWORD_DEFAULT - 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).

  • PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.

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