Building a Secured Usexr Authentication System with PHP, MySQL, PDO, and Hashed Passwords



Introduction:

User authentication is fundamental for ensuring the security and integrity of web applications. By implementing a robust authentication system, developers can safeguard user data and prevent unauthorized access. In this guide, we'll explore how to construct a secure user authentication system using PHP, MySQL, PDO (PHP Data Objects), and hashed passwords, ensuring both functionality and security.


1. Setting up the Database:

Before diving into coding, let's establish the database structure to store user information securely. We'll create a table to hold user credentials, including usernames, email addresses, hashed passwords, and other relevant data.


Example SQL Schema:

CREATE TABLE users (

    id INT AUTO_INCREMENT PRIMARY KEY,

    username VARCHAR(50) NOT NULL UNIQUE,

    email VARCHAR(100) NOT NULL UNIQUE,

    password VARCHAR(255) NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);


2. Establishing PDO Connection:

PDO provides a flexible and secure way to interact with the database. We'll establish a connection to the MySQL database using PDO, ensuring that our application is protected against SQL injection attacks.


**Example PHP Code for PDO Connection:**

<?php

$host = 'localhost';

$dbname = 'your_database';

$username = 'your_username';

$password = 'your_password';


try {

    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    // Set PDO to throw exceptions on error

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

    die("Connection failed: " . $e->getMessage());

}

?>


3. Hashing Passwords for Security:

Storing passwords in plain text poses a significant security risk. Instead, we'll use cryptographic hashing algorithms like bcrypt to securely hash passwords before storing them in the database.


Example Code to Hash Passwords:

$password = 'user_password';

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);


4. User Registration:

Create a user registration form where users can sign up for an account by providing a username, email, and password. Upon submission, the system will hash the password and store the user's credentials in the database.


Example PHP Code for User Registration:

<?php

// Process registration form submission

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = $_POST['username'];

    $email = $_POST['email'];

    $password = $_POST['password'];


    // Hash the password

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);


    // Insert user data into the database

    $stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");

    $stmt->execute([$username, $email, $hashedPassword]);


    // Redirect to login page

    header('Location: login.php');

    exit;

}

?>


5. User Login:

Implement a login form where users can authenticate themselves by providing their username and password. Upon submission, the system will verify the credentials against the hashed password stored in the database.


Example PHP Code for User Login:

<?php

// Process login form submission

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = $_POST['username'];

    $password = $_POST['password'];


    // Retrieve hashed password from the database

    $stmt = $pdo->prepare("SELECT id, username, password FROM users WHERE username = ?");

    $stmt->execute([$username]);

    $user = $stmt->fetch();


    // Verify password

    if ($user && password_verify($password, $user['password'])) {

        // Password is correct, log the user in

        $_SESSION['user_id'] = $user['id'];

        header('Location: dashboard.php');

        exit;

    } else {

        // Invalid username or password

        $error = "Invalid username or password";

    }

}

?>


Conclusion:

Building a secure user authentication system is crucial for protecting user data and maintaining the integrity of web applications. By following the steps outlined in this guide and incorporating features such as password hashing, PDO database connection, and secure user registration and login processes, developers can create a robust authentication system that meets the highest standards of security and functionality.