What are the best practices for securely handling user passwords in a PHP application?
To securely handle user passwords in a PHP application, it is recommended to hash the passwords using a strong hashing algorithm like bcrypt, salt the passwords before hashing to add an extra layer of security, and store the hashed passwords in a secure database. Additionally, use prepared statements to prevent SQL injection attacks when querying the database for user authentication.
// Hash and salt the user password before storing it in the database
$password = $_POST['password'];
$salt = openssl_random_pseudo_bytes(22); // Generate a random salt
$options = [
'cost' => 12,
'salt' => $salt,
];
$hashed_password = password_hash($password, PASSWORD_BCRYPT, $options);
// Store the hashed password and salt in the database
$stmt = $pdo->prepare("INSERT INTO users (username, password, salt) VALUES (?, ?, ?)");
$stmt->execute([$username, $hashed_password, $salt]);