How to implement user authentication and secure password storage using PDO in PHP?

To implement user authentication and secure password storage using PDO in PHP, you can follow these steps:

  1. Create a database table to store user information, such as username, password hash, and any additional user data.

  2. 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);
  1. Create a registration form where users can sign up with a username and password.

  2. When a user submits the registration form, retrieve the username and password from the form fields.

$username = $_POST['username']; $password = $_POST['password'];
  1. Generate a hash of the password using PHP's password_hash() function.
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
  1. Prepare an INSERT statement to store the user information in the database. Bind the parameters to prevent SQL injection attacks.
$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();
  1. Create a login form where users can enter their username and password.

  2. When a user submits the login form, retrieve the username and password from the form fields.

$username = $_POST['username']; $password = $_POST['password'];
  1. Prepare a SELECT statement to retrieve the user's password hash from the database based on the provided username.
$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 }
  1. Use password_verify() function to compare the entered password with the stored password hash.

  2. 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.