How to store passwords securely in PHP?
Never save the real password. Save a hash of it. In PHP use password_hash() to create the hash and password_verify() to check a password at login.
<?php
$password = "MySecret@123";
// Save this hash in the database
$hash = password_hash($password, PASSWORD_DEFAULT);
// At login, compare the typed password with the saved hash
var_dump(password_verify("MySecret@123", $hash));
var_dump(password_verify("wrong-password", $hash));
?>
Output:
Tutorials Class - Output Window
bool(true)
bool(false)
- Do not use
md5()orsha1()for passwords. They are very fast, so attackers can try billions of guesses per second. - password_hash() adds a random salt itself, you do not need to create one.
- The hash can be long, so use a
VARCHAR(255)column. - Use
password_needs_rehash()to upgrade old hashes when PHP changes the default algorithm.
Related: PHP Security Tips.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |