How to store and validate a password

Two functions for working with passwords

Function Description
password_hash($password, $algorithm) Creates a new hash of the password using a strong salt and a strong one-way encryption algorithm.
password_verify($password, $hash Returns TRUE if the specified password matches the specified hash.

Two constants for setting the algorithm for the password

Constant Description
PASSWORD_BCRYPT Uses the bcrypt algorithm to create a hash that’s 60 characters long.
PASSWORD_DEFAULT Uses the default algorithm of the password_hash() function. With PHP 5.5 and 7.1, the default algorithm is bcrypt. However, this default may change as newer and stronger algorithms become available. This may cause the number of characters in the hash to increase beyond the current 60 characters.

Code that hashes a password using the default algorithm

      $password = 's3sam3'; 
      $hash = password_hash($password, PASSWORD_DEFAULT); // up to 255 chars
      

Code that verifies whether a password is valid

      $valid_password = password_verify('s3sam3', 
                        '$2y$10$xIqN2cVy8HVuKNKUwxFQR.xRP9oRj.FF8r52spVc.XCaEFy7iLHmu');
      if ($valid_password) { 
        echo("Password is valid.</p>");
      }
      

Description

Back