To build a secure user authentication system, we will focus on the following key areas:

  1. Password Hashing: Storing passwords securely.
  2. Session Management: Maintaining user sessions safely.
  3. Input Validation: Protecting against common attacks like SQL injection.

1. Password Hashing

Storing passwords in plaintext is a significant security risk. Instead, we will use PHP's built-in password_hash() and password_verify() functions to handle password hashing securely.

Example: Registering a User

When a user registers, we will hash their password before storing it in the database.

<?php
// Database connection
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';

$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// User registration
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Hash the password
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Insert user into the database
    $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $hashedPassword);
    $stmt->execute();

    echo "User registered successfully!";
}
?>

2. Session Management

Once a user is authenticated, we need to manage their session securely. This involves starting a session and storing user information.

Example: User Login

During login, we will verify the user's credentials and start a session.

<?php
session_start();

// User login
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Fetch user from the database
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // Verify password
    if ($user && password_verify($password, $user['password'])) {
        // Store user information in session
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        echo "Login successful!";
    } else {
        echo "Invalid username or password!";
    }
}
?>

3. Input Validation

Validating user input is crucial to prevent attacks such as SQL injection. Always sanitize and validate inputs before processing them.

Example: Validating Input

function sanitizeInput($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

// Usage
$username = sanitizeInput($_POST['username']);
$password = sanitizeInput($_POST['password']);

Best Practices for Secure Authentication

PracticeDescription
Use HTTPSAlways serve your application over HTTPS to encrypt data in transit.
Implement Rate LimitingPrevent brute-force attacks by limiting login attempts from a single IP.
Use Secure CookiesSet the HttpOnly and Secure flags on session cookies to enhance security.
Regularly Update DependenciesKeep your PHP version and libraries up to date to mitigate vulnerabilities.

Conclusion

Implementing secure user authentication in PHP involves careful handling of passwords, managing sessions securely, and validating user inputs. By following best practices, you can create a robust authentication system that protects user data and enhances the overall security of your application.

Learn more with useful resources