how to salt a password in php

To salt a password in PHP, you can use the password_hash function. This function generates a secure hash of the password and includes a random salt to make the hash unique.

Here's an example:

main.php
$password = 'mypassword';
$salt = uniqid(); // generate a unique salt

$hashed_password = password_hash($password . $salt, PASSWORD_DEFAULT);

// $hashed_password now contains a hashed version of the password with salt
219 chars
7 lines

In this example, we first generate a unique salt using the uniqid function. We then concatenate the password and salt and pass them to password_hash along with the PASSWORD_DEFAULT option. This results in a securely hashed password that includes the salt.

To verify a password, you can use the password_verify function:

main.php
$check_password = 'mypassword';
if (password_verify($check_password . $salt, $hashed_password)) {
    // password is correct
} else {
    // password is incorrect
}
165 chars
7 lines

Here, we concatenate the password and salt again and pass them to password_verify along with the hashed password. If the password matches, the function returns true, otherwise it returns false. This method of including a unique salt with each password ensures that even if two users have the same password, their hashes will be different, making it much harder for attackers to exploit any password leaks.

gistlibby LogSnag