How does the method of password verification differ when using a database compared to a .txt file in PHP?
When using a database for password verification in PHP, the passwords are typically stored in a hashed format for security reasons. This means that when a user logs in, their entered password is hashed and compared to the hashed password stored in the database. On the other hand, when using a .txt file for password verification, the passwords are often stored in plain text, which is not secure. Therefore, it is recommended to use a database for storing and verifying passwords in PHP.
// Database method for password verification
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $pdo->prepare("SELECT password FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
echo "Login successful!";
} else {
echo "Invalid username or password.";
}