PHP5 password_hash()

Udemy Generic 728x90

(PHP 5 >= 5.5.0)

Overview

Finally, new version of php come up with security concerns, since crypt() is secure but has many warnings. Now, with new function password_hash() creates a new password hash using a strong one-way hashing algorithm.

This function takes the user’s password, and hashes it using the current best algorithm (bcrypt, as of writing this), and a securely created salt.

password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

Syntax

string password_hash ( string $password , integer $algo , array $options )

  • $password
    • the user’s password
  • $algo
    • A algo constant denoting the algorithm to use when hashing the password.
  • $options
    • An associative array containing options.
    • If omitted, a random salt will be created and the default cost will be used.

Description

  • The first parameter is the password string that needs to be hashed and the second parameter specifies the algorithm that should be used for generating the hash.
  • The default algorithm is currently bcrypt, but a stronger algorithm may be added as the default later at some point in the future and may generate a larger string.
  • If you are using PASSWORD_DEFAULT in your projects, be sure to store the hash in a column that’s capacity is beyond 60 characters. Setting the column size to 255 might be a good choice.
  • You could also use PASSWORD_BCRYPT as the second parameter. In this case the result will always be 60 characters long.
  • The important thing here is that you don’t have to provide a salt value or a cost parameter. The new API will take care of all of that for you. And the salt is part of the hash, so you don’t have to store it separately.
  • If you want to provide your own salt (or cost), you can do so by passing a third argument to the function, an array of options.

 

Example

</p>
<p>&lt;?php</p>
<p>$options = [</p>
<p>   'salt'=&gt; custom_function_for_salt(),//write your own code to generate a suitable salt</p>
<p>   'cost'=&gt;12// the default cost is 10</p>
<p>];</p>
<p>$hash = password_hash($password, PASSWORD_DEFAULT, $options);</p>
<p>&lt;span style=&quot;color: #262626;&quot;&gt;

 

Udemy Generic 728x90

Spread the word. Share this post!