PHP

Secure Password Hashing with Argon2 (PHP)

Learn to securely hash user passwords in PHP using `password_hash` with Argon2, protecting against rainbow table and brute-force attacks.

<?php
// Generate a secure password hash
function createPasswordHash(string $password): string {
    return password_hash($password, PASSWORD_ARGON2ID);
}

// Verify a password against its hash
function verifyPassword(string $password, string $hash): bool {
    return password_verify($password, $hash);
}

// --- Usage Example ---
$userPassword = "MyS3cur3P@ssw0rd!";

// Hash the password for storage
$hashedPassword = createPasswordHash($userPassword);
echo "Hashed Password: " . $hashedPassword . "
";

// Simulate login attempt
$loginAttemptPassword = "MyS3cur3P@ssw0rd!"; // Correct password
if (verifyPassword($loginAttemptPassword, $hashedPassword)) {
    echo "Password verification successful!
";
} else {
    echo "Password verification failed.
";
}

$incorrectPassword = "WrongPassword!"; // Incorrect password
if (verifyPassword($incorrectPassword, $hashedPassword)) {
    echo "Incorrect password verification successful (ERROR).
";
} else {
    echo "Incorrect password verification failed (CORRECT).
";
}

// Rehash if needed (e.g., algorithm update or cost change)
if (password_needs_rehash($hashedPassword, PASSWORD_ARGON2ID)) {
    $newHashedPassword = createPasswordHash($userPassword);
    echo "Password rehashed: " . $newHashedPassword . "
";
    // Update the stored hash in the database
}
?>
How it works: This snippet demonstrates how to securely hash and verify user passwords in PHP using the `password_hash` and `password_verify` functions with the recommended `PASSWORD_ARGON2ID` algorithm. Argon2 is resistant to GPU-based attacks and is a strong choice for password storage. It also includes `password_needs_rehash` for updating hashes without requiring users to reset their passwords.

Need help integrating this into your project?

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

Hire DigitalCodeLabs