Logo Logo
Back to list
WEB

How to Securely Store Passwords in PHP: Forget MD5!

21. 03. 2026
How to Securely Store Passwords in PHP: Forget MD5!

User data security is priority number one. The most important rule when working with passwords is: Never store passwords in a database as plain text! If someone breached your database, they would see all your users' passwords.

Why not use MD5 or SHA1?

Old methods like MD5 or SHA1 are now too fast and too vulnerable. Modern computers can guess millions of such passwords in seconds using "rainbow tables".

The Modern Solution: password_hash()

PHP offers a built-in function called password_hash(), which uses a strong algorithm (Bcrypt by default). This function automatically handles "salting," meaning the result for the same password will be different every time.

// Storing a password in the database
$password = "mySecurePassword123";
$hash = password_hash($password, PASSWORD_DEFAULT);

// The result is a long string of characters to be stored in a MySQL column (VARCHAR 255)
echo $hash; 

Verifying the Password During Login

When a user tries to log in, you cannot simply compare two passwords. You must use the password_verify() function.

// Verifying during login
$entered_password = "mySecurePassword123";
$hash_from_db = "...content_from_db...";

if (password_verify($entered_password, $hash_from_db)) {
echo "Password is correct!";
} else {
echo "Incorrect password!";
}

More about password_hash can be found in my tutorial at this link: password_hash.

Hvala za obisk! Dodajam politiko zasebnosti.

© 2024 Vse pravice pridržane.

Vam je koda pomagala? Če želite podpreti moj trud pri pripravi vodičev in vzdrževanju strani, mi lahko namenite donacijo za kavo.