Home >Backend Development >PHP Tutorial >How Can PHP 5.5's `password_hash()` and `password_verify()` Securely Store and Verify User Passwords?

How Can PHP 5.5's `password_hash()` and `password_verify()` Securely Store and Verify User Passwords?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 04:00:14305browse

How Can PHP 5.5's `password_hash()` and `password_verify()` Securely Store and Verify User Passwords?

Password Storage and Verification with PHP 5.5

When securing user passwords, it's essential to employ robust encryption techniques to prevent unauthorized access. PHP 5.5 introduced the password_hash() and password_verify() functions for this purpose, offering a convenient and secure solution for password handling.

Correct Password Storage

The provided code demonstrates an incorrect approach to password storage. You should not store the salt separately but rather store both the hash and salt. The password_hash() function generates a string that incorporates both elements.

The correct way to store the password is:

$hashAndSalt = password_hash($password, PASSWORD_BCRYPT);
// Insert $hashAndSalt into the database

Password Verification

To verify the password, retrieve the previously stored $hashAndSalt from the database and use it with the password_verify() function:

if (password_verify($password, $hashAndSalt)) {
    // Verified
}

Additional Security Considerations

While the password_hash() function provides a secure password storage mechanism, it's important to adhere to other security best practices. Consider using:

  • mysqli extension instead of mysql (deprecated in PHP5.5)
  • Input validation to prevent SQL injection

The above is the detailed content of How Can PHP 5.5's `password_hash()` and `password_verify()` Securely Store and Verify User Passwords?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn