← Back to all snippets
PHP

Secure Password Hashing and Verification with PHP Bcrypt

Implement strong password security in PHP using `password_hash()` with Bcrypt for hashing and `password_verify()` for secure authentication.

<?php
// User provides a plain-text password
$plainTextPassword = 'MySecretPassword123!';

// --- Hashing a password ---
// Use PASSWORD_BCRYPT (default, recommended)
// The 'cost' factor determines how much CPU time to spend hashing.
// A higher cost means more time, making brute-force attacks harder.
// Choose a cost that takes around 200-500ms on your server.
$options = [
    'cost' => 12, // Example cost. Adjust based on your server's performance.
];
$hashedPassword = password_hash($plainTextPassword, PASSWORD_BCRYPT, $options);

if ($hashedPassword === false) {
    die("Password hashing failed.");
}

echo "Original Password: " . $plainTextPassword . "
";
echo "Hashed Password: " . $hashedPassword . "

";

// --- Verifying a password ---
// Simulate a login attempt with a user-provided password
$userAttemptPassword = 'MySecretPassword123!'; // Correct password
// $userAttemptPassword = 'WrongPassword'; // Incorrect password

if (password_verify($userAttemptPassword, $hashedPassword)) {
    echo "Password verification successful! User logged in.
";

    // Optional: Rehash password if the algorithm or cost needs updating
    // This makes sure passwords are always stored with the latest/strongest settings
    if (password_needs_rehash($hashedPassword, PASSWORD_BCRYPT, $options)) {
        $newHashedPassword = password_hash($userAttemptPassword, PASSWORD_BCRYPT, $options);
        // Update the user's password in the database with $newHashedPassword
        echo "Password rehashed and updated in the database.
";
    }

} else {
    echo "Password verification failed! Invalid credentials.
";
}
?>
How it works: Storing plain-text passwords is a severe security risk. This snippet demonstrates secure password handling in PHP using `password_hash()` for hashing and `password_verify()` for checking user-provided passwords against their stored hashes. `PASSWORD_BCRYPT` is recommended because it is a slow, adaptive hashing algorithm that incorporates a random salt, making it resistant to brute-force attacks and rainbow table lookups. The `cost` parameter allows you to adjust the computational intensity. `password_needs_rehash()` helps keep password security up-to-date.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs