PHP

Securely Hash Passwords with Bcrypt in PHP

Learn how to securely hash user passwords using PHP's `password_hash` function with the Bcrypt algorithm, preventing rainbow table attacks and making brute-forcing difficult.

<?php

/**
 * Hashes a plaintext password using the Bcrypt algorithm.
 * @param string $password The plaintext password.
 * @return string The hashed password.
 */
function hashPassword(string $password): string
{
    // PASSWORD_BCRYPT is currently the strongest algorithm provided by password_hash
    // PASSWORD_DEFAULT constantly updates to the strongest available hash algorithm
    return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}

/**
 * Verifies a plaintext password against a stored hashed password.
 * @param string $password The plaintext password to check.
 * @param string $hashedPassword The hashed password from the database.
 * @return bool True if the password matches, false otherwise.
 */
function verifyPassword(string $password, string $hashedPassword): bool
{
    return password_verify($password, $hashedPassword);
}

// Example Usage:
$userPassword = 'MySuperSecurePassword123!';
$hashedPswd = hashPassword($userPassword);

echo "Original Password: " . $userPassword . "
";
echo "Hashed Password: " . $hashedPswd . "
";

// Simulate user login attempt
$loginAttempt = 'MySuperSecurePassword123!';
if (verifyPassword($loginAttempt, $hashedPswd)) {
    echo "Login successful!
";
} else {
    echo "Login failed!
";
}

// Simulate wrong password
$wrongAttempt = 'WrongPassword456';
if (verifyPassword($wrongAttempt, $hashedPswd)) {
    echo "Login successful (this should not happen)!
";
} else {
    echo "Login failed (as expected)!
";
}

// Optionally rehash if the cost factor needs to be updated or algorithm changed
if (password_needs_rehash($hashedPswd, PASSWORD_BCRYPT, ['cost' => 13])) {
    $newHashedPswd = hashPassword($userPassword); // using the same original password
    echo "Password needs rehash. New hash: " . $newHashedPswd . "
";
}

?>
How it works: This PHP snippet demonstrates how to securely hash and verify user passwords using `password_hash` and `password_verify` functions. It leverages the Bcrypt algorithm (recommended for its robustness and adaptive nature) and a configurable cost factor. Storing passwords as secure hashes, not plaintext, is critical to protect user data even if your database is compromised. The `password_needs_rehash` function also allows for automatically updating hashes to stronger configurations over time.

Need help integrating this into your project?

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

Hire DigitalCodeLabs