Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - password_hash Function



ThePHP Hashing password_hash()function is used to create a password hash using the given default password and a strong "one-way" hashing algorithm. A password hash is a secure way to store passwords by transforming them into a fixed-length string of characters, which is normally not reversible.

This function is compatible with the crypt() function, therefore, password hashes created by the crypt() function can be used with the password_hash() function.

It accepts three parameters. If the "options" parameter is omitted, a random salt will be created, and the default cost will be used.

Syntax

Following is the syntax of the PHP Hashing password_hash() function −

password_hash(string $password, string $algo, array $options = []): string

Parameters

Following are the parameters of this function −

  • password − The given users password.
  • algo − Apassword algorithm constantrepresents the algorithm used when hashing the password.
  • options − An associative array containing options.

Return value

This function returns the hash password.

Example 1

Following is the basic example of the PHP Hashing password_hash() function −

<?php	
   $passw = "53nh46u74m3nt3";
   echo "Given password: $passw";
   $opts = [ "cost" => 15 ];
   echo "\nGenerating password hash.....";
   $hashp = password_hash($passw, PASSWORD_BCRYPT, $opts);
   echo "\nGenerated password hash: $hashp";
   echo "\nPassword length: ".strlen($hashp);
?>

Output

After executing the above program the following output will be displayed −

Given password: 53nh46u74m3nt3
Generating password hash.....
Generated password hash: $2y$15$4lM81sKwdN9vCLUKQ2h2yup.vZVcFwaa2.lCOG.Fg1.bo1X/MZvJy
Password length: 60

Example 2

Following is another example of the PHP Hashing password_hash() function. We use this function to create a password hash from the given password "53nh46u74m3nt3". If we pass the custom salt parameter, it will throw an error, since it is no longer supported −

<?php	
   $passw = "53nh46u74m3nt3";
   echo "Given password: $passw";
   $opts = [ "cost" => 15, "salt" => "salteadoususuueyryy28yyGGtttwqtwtt" ];
   echo "\nGenerating password hash.....";
   $hashp = password_hash($passw, PASSWORD_BCRYPT, $opts);
   echo "\nGenerated password hash: $hashp";
   echo "\nPassword length: ".strlen($hashp);
?>

Output

The above program produces the following output −

Given password: 53nh46u74m3nt3
Generating password hash.....
Generated password hash: $2y$15$woSgOZK/0Y3Qj/7iAxD0Bee2O3ohaaufBcq46gwlVRw0dNoR01vpi
Password length: 60
PHP Warning:  password_hash(): The "salt" option has been ignored, 
since providing a custom salt is no longer supported in /home/cg/root/55817/main.php on line 6
php_function_reference.htm
Advertisements