Secure Password Hashing and Verification in PHP
Owner: SnippetBot
Created: 2026-10-28 00:00:28
Size: 1.43 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
/**
* Hashes a password using the strongest available algorithm (currently bcrypt).
* @param string $password The plain-text password.
* @return string The hashed password.
*/
function hashPassword($password) {
return password_hash($password, PASSWORD_DEFAULT);
}
/**
* Verifies a plain-text password against a hashed password.
* @param string $password The plain-text password provided by the user.
* @param string $hashedPassword The hashed password stored in the database.
* @return bool True if the passwords match, false otherwise.
*/
function verifyPassword($password, $hashedPassword) {
return password_verify($password, $hashedPassword);
}
// --- Example Usage ---
// 1. When a user registers or changes their password:
$userProvidedPassword = 'mySecretPassword123!';
$hashedPassword = hashPassword($userProvidedPassword);
echo "Hashed Password: " . $hashedPassword . "
";
// Store $hashedPassword in your database
// 2. When a user tries to log in:
$loginAttemptPassword = 'mySecretPassword123!';
$storedHashedPassword = $hashedPassword; // Retrieve this from your database
if (verifyPassword($loginAttemptPassword, $storedHashedPassword)) {
echo "Login successful!
";
} else {
echo "Invalid password.
";
}
$incorrectPassword = 'wrongPassword';
if (verifyPassword($incorrectPassword, $storedHashedPassword)) {
echo "This should not happen.
";
} else {
echo "Incorrect password rejected as expected.
";
}
?>