create a password in php

To create a secure password in PHP, we need to hash the password. Hashing is a process of converting plaintext passwords into unintelligible strings that can't be reversed. We can use one of the built-in hashing functions in PHP such as password_hash().

main.php
$password = 'password123';
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash; // output: $2y$10$TV..r5xJfu5Rwzypkl5st.cigZry/m1CKxlLRGG/LlmgfgZOq9QyO
163 chars
4 lines

In the above example, we have first created a plaintext password string. We then pass this password to the password_hash() function along with the hashing algorithm to be used. In this case, we have used the PASSWORD_DEFAULT algorithm, which currently is bcrypt. The function then returns the hashed password string which is then stored in the database.

When a user logs in and enters their password, we can then match their plain text password with the hashed version using password_verify() function.

main.php
$login_password = 'password123';
$stored_hash = '$2y$10$TV..r5xJfu5Rwzypkl5st.cigZry/m1CKxlLRGG/LlmgfgZOq9QyO';

if (password_verify($login_password, $stored_hash)) {
    // Password is correct
} else {
    // Password is incorrect
}
234 chars
9 lines

In the above example, we have a stored hash value from the database and a plain text password entered by the user during login. We then use the password_verify() function to check if the entered password matches the stored hash. If they match, then the user is logged in successfully.

gistlibby LogSnag