PHP

Secure Password Hashing with PHP's password_hash

Learn to securely hash user passwords using PHP's built-in `password_hash` function, protecting against rainbow table attacks and brute-force attempts.

<?php
// Hashing a password
$password = 'mySuperSecretPassword123!';
$hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

// Storing $hashedPassword in your database
echo "Hashed Password: " . $hashedPassword . "
";

// Verifying a password
$inputPassword = 'mySuperSecretPassword123!'; // User's input from login form
if (password_verify($inputPassword, $hashedPassword)) {
    echo "Password is valid!
";
} else {
    echo "Invalid password.
";
}

// Re-hashing if algorithm/cost changes or to periodically update older hashes
if (password_needs_rehash($hashedPassword, PASSWORD_BCRYPT, ['cost' => 12])) {
    $newHashedPassword = password_hash($inputPassword, PASSWORD_BCRYPT, ['cost' => 12]);
    // Update the database with $newHashedPassword
    echo "Password re-hashed to: " . $newHashedPassword . "
";
}
How it works: This snippet demonstrates the secure way to handle user passwords in PHP using the `password_hash()` and `password_verify()` functions. `password_hash()` uses a strong, one-way hashing algorithm (like bcrypt, specified by `PASSWORD_BCRYPT`) with a built-in salt to generate a unique hash for each password. The `cost` parameter controls the computational intensity, making brute-force attacks harder. `password_verify()` safely checks if a given plain-text password matches a stored hash without revealing the original password, and `password_needs_rehash()` helps keep hashes up-to-date with current best practices.

Need help integrating this into your project?

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

Hire DigitalCodeLabs