Introduction
PHP password_hash is a built-in function that is majorly used to encrypt the password string.
Encryption has c combination of random letters, numbers, and special characters.
PHP password_hash() function can create a unique password hash using a strong hashing algorithm which is only one-way hashing or encryption.
One-way hashing means, that generated password can not be decrypted.
In this article, we learn, to complete the PHP password hash concept and use the password verify function to confirm whether the password is correct or not with the help of an example.
Syntax:
The password hash function takes a maximum of 3 parameters.
1 2 |
string password_hash($string, $algo, $options) |
- $string parameter takes the user’s password string which is used to hash and store on DB.
- $algo this parameter supports integer values that refer to some built-in PHP password hashing algos,
- PASSWORD_DEFAULT: This is the default option and is recommended also. Because of developers when they want to add new algo options.
- PASSWORD_BCRYPT: This algo uses the CRYPT_BLOWFISH algorithm to generate the hash.
- PASSWORD_ARGON2I: Used Argon2 hashing algo.
- $options take some optional and advanced options like cost and salt.
- Cost: for PASSWORD_BCRYPT it is the maximum algorithmic cost to be applied. 10 is the default. And it also affects the speed and loading time of the script.
- Cost: For PASSWORD_ARGON2I maximum memory cost is to be applied to generate any hash.
- Salt can be provided manually but is not recommended.
Example of PHP Password Hash
1 2 3 4 5 6 7 8 |
$str = 'myPassword'; $options = [ 'cost' => 10, 'salt' => '$P27r06o9!nasda57b2M22' ]; echo sprintf("Result of crypt() on %s is %s\n", $str, crypt($str, $options['salt'])); |
Output:
Result of crypt() on myPassword is $PjPYbvqoH26U
PHP password_hash and password_verify Example
1 2 3 4 5 6 7 8 9 10 |
<?php $password = 123; echo $hashed_password = password_hash($password, PASSWORD_DEFAULT); if(password_verify($password, $hashed_password)) { // If the password inputs matched the hashed password in the database echo "Password verified"; } |
Output:
$2y$10$dh8ntY.BhgCarjZuEwG70.vFLt4Af6vz08Ibd9TsMRv/4PegCJToS
Password verified
PHP password_verify Function
PHP password_verify Function is used to check the hashed password and verify whether it is matching with the original password or not.
Syntax:
1 |
password_verify(string $password, string $hash) |
Password verification takes only 2 parameters, one is input password by a user, and hashed password from DB.
Please let me know if you have to face any issues at the time of implementation.
To know more about PHP encryption algorithms, check here PHP: Password Hashing Functions – Manual.
Happy Coding..!
[…] PHP password_hash, password_verify With Example – PHPCODER … […]