To implement user authentication and secure password storage using PDO in PHP, you can follow these steps:
Create a database table to store user information, such as username, password hash, and any additional user data.
Establish a PDO connection to your database by creating a new PDO object, passing in the database connection details.
$host = 'localhost';
$db = 'mydb';
$user = 'username';
$pass = 'password';
// Create a PDO instance
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
Create a registration form where users can sign up with a username and password.
When a user submits the registration form, retrieve the username and password from the form fields.
$username = $_POST['username'];
$password = $_POST['password'];
password_hash()
function.$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $passwordHash, PDO::PARAM_STR);
$stmt->execute();
Create a login form where users can enter their username and password.
When a user submits the login form, retrieve the username and password from the form fields.
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $dbh->prepare("SELECT password FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$result || !password_verify($password, $result['password'])) {
// Invalid username or password
} else {
// Successful login
}
Use password_verify()
function to compare the entered password with the stored password hash.
If the entered password matches the stored hash, perform the desired actions, such as creating a session variable to indicate that the user is logged in.
This implementation ensures secure password storage by using PHP's built-in password hashing functions and protects against SQL injection attacks by utilizing prepared statements with bound parameters.