password_hash()

password_hash() is the basic function for the password hashing functions. It takes two arugments, the string (password) to hash, and the encryption method. I recommend you use PASSWORD_DEFAULT as the encryption method. Currently this defaults to BCRYPT (strongest), but if a better algorithm comes out, it will automatically update your application for you. So, your example code looks like password_hash( "my_password", PASSWORD_DEFAULT );.

One of the most powerful features of hashing is that time effects the hash output. Let's examine this further.

Results:

Please supply a password first.

password_verify()

password_verify() is the function for verifying a password hash. This is the only way to verify the password is correct because no other PHP equality checks ( == OR === ) account for the time factor with the hash. This function takes two arugments, the plain text string (password) to hash, and the (saved) hash to compare it to. You would likely get the second argument as a value from a database. So, your example code looks like password_verify( "my_password", $savedHashInDatabase );.

Let us now compare passwords. Try entering a random password. Then, after submitting, try entering "phpmadison" as your password. (No quotes).

Results:

Please supply a password first.

password_needs_rehash()

password_needs_rehash() is the function used to determine if it's time to update the hash. This isn't something you need to check for every time, but it's a good idea to implement this in your login script such that it runs once a month or something of the like. A password may need a rehash if a hashing algorithm changes, your hosting performance changes (the more powerful machine, the stronger the hash), or other reasons. You need to know the original algorithm it was hashed with to use this. I have sample code for this below, but I leave this to you to find an example to test this with.

if (password_verify($password, $hash)) {
   if (password_needs_rehash($hash, $algorithm, $options)) {
      $hash = password_hash($password, $algorithm, $options);
      /* Store new hash in db */
   }
}