How can PHP be used to securely hash and salt passwords for user authentication?

To securely hash and salt passwords for user authentication in PHP, you can use the password_hash() function to generate a secure hash and include a unique salt for each user. This helps protect against common attacks like rainbow tables and brute force attacks.

// Generate a random salt
$salt = random_bytes(16);

// Hash the password with bcrypt algorithm and the generated salt
$hashed_password = password_hash($password, PASSWORD_BCRYPT, ['salt' => $salt]);

// Verify the password
if (password_verify($password, $hashed_password)) {
    // Password is correct
} else {
    // Password is incorrect
}