PHP
Securely Hash Passwords with Bcrypt
Discover how to securely store user passwords using the Bcrypt hashing algorithm, preventing plaintext storage and enhancing application security against breaches.
<?php
$password = "MySuperSecretPassword123!";
// Hash the password using Bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
echo "Original password: " . $password . "
";
echo "Hashed password: " . $hashed_password . "
";
// Verify a password against the hash
$user_attempt = "MySuperSecretPassword123!"; // Password provided by user on login
if (password_verify($user_attempt, $hashed_password)) {
echo "Password verified successfully!";
} else {
echo "Invalid password.";
}
?>
How it works: This snippet demonstrates the secure way to handle passwords in PHP using `password_hash()` and `password_verify()`. `password_hash()` uses the robust Bcrypt algorithm (defaulting to a secure random salt and a configurable cost factor) to create a one-way hash. `password_verify()` safely checks a user's login attempt against the stored hash without needing to store the plaintext password, crucial for protecting user credentials.