PHP

Securely Hash and Verify Passwords in PHP

Learn to securely hash user passwords using PHP's password_hash() and verify them with password_verify() to protect against common attacks.

<?php
function hashPassword(string $password): string
{
    return password_hash($password, PASSWORD_DEFAULT);
}

function verifyPassword(string $password, string $hashedPassword): bool
{
    return password_verify($password, $hashedPassword);
}

// Usage example:
$userPassword = 'mySecretPassword123';
$hashed = hashPassword($userPassword);
echo "Hashed password: " . $hashed . "
";

if (verifyPassword($userPassword, $hashed)) {
    echo "Password verified successfully!
";
} else {
    echo "Password verification failed.
";
}

// Simulate incorrect password
if (verifyPassword('wrongPassword', $hashed)) {
    echo "Incorrect password verified (ERROR)!
";
} else {
    echo "Incorrect password correctly rejected.
";
}
?>
How it works: This snippet demonstrates how to securely hash passwords using PHP's built-in password_hash() function and verify them with password_verify(). Using PASSWORD_DEFAULT ensures the strongest, most up-to-date hashing algorithm is used, automatically handling salting and iteration counts. This method is crucial for protecting user credentials against rainbow table attacks and brute-force attempts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs