phpsalt-cryptographypassword-hashphp-password-hash

How to use PHP's password_hash to hash and verify passwords


Recently I have been trying to implement my own security on a log in script I stumbled upon on the internet. After struggling of trying to learn how to make my own script to generate a salt for each user, I stumbled upon password_hash.

From what I understand (based off of the reading on this page), salt is already generated in the row when you use password_hash. Is this true?

Another question I had was, wouldn't it be smart to have 2 salts? One directly in the file and one in the DB? That way, if someone compromises your salt in the DB, you still have the one directly in the file? I read on here that storing salts is never a smart idea, but it always confused me what people meant by that.


Solution

  • Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

    Let's say we have the following input:

    $password = $_POST['password'];
    

    You first hash the password by doing this:

    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    

    Then see the output:

    var_dump($hashed_password);
    

    As you can see it's hashed. (I assume you did those steps).

    Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

    // Query the database for username and password
    // ...
    
    if(password_verify($password, $hashed_password)) {
        // If the password inputs matched the hashed password in the database
        // Do something, you know... log them in.
    } 
    
    // Else, Redirect them back to the login page.
    

    Official Reference