Home >Database >Mysql Tutorial >How Can PHP 5.5's `password_hash()` and `password_verify()` Secure Password Storage?

How Can PHP 5.5's `password_hash()` and `password_verify()` Secure Password Storage?

DDD
DDDOriginal
2024-12-22 21:49:18455browse

How Can PHP 5.5's `password_hash()` and `password_verify()` Secure Password Storage?

Using PHP 5.5's password_hash and password_verify Functions to Secure Password Storage

Storing passwords securely is crucial for maintaining user data integrity. PHP 5.5 introduced the password_hash() and password_verify() functions to provide a secure and efficient way to do this.

password_hash() and Salt

Unlike older password storage methods, password_hash() employs a unique salt for each password. A salt is a random string that prevents rainbow table attacks, where attackers try common password hashes.

Storing Password and Salt

To store a password with PHP 5.5's password_hash(), follow these steps:

  1. Generate a salt using uniqid() or a similar function.
  2. Call password_hash() with the password, PASSWORD_BCRYPT, and the options array containing the salt and a cost (recommended: 10-12).
  3. The password_hash() function will return a hashed string that includes both the hash and the salt.

Example:

$options = ["cost" => 10, "salt" => uniqid()];
$hashAndSalt = password_hash($password, PASSWORD_BCRYPT, $options);

Verifying Password

To verify a password, fetch the stored hashAndSalt from the database and call password_verify() with the provided password and the stored hashAndSalt.

Example:

if (password_verify($password, $hashAndSalt)) {
    // Password verified successfully
}

Additional Security Measures

While password_hash() provides a secure way to store passwords, it's recommended to:

  • Use a cost parameter of 10 or higher.
  • Use mysqli instead of mysql for database handling.
  • Implement SQL injection protection techniques.

The above is the detailed content of How Can PHP 5.5's `password_hash()` and `password_verify()` Secure Password Storage?. 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