To create a robust authentication system, we will cover the following key aspects:

  1. User Registration
  2. User Login
  3. Password Hashing
  4. Session Management
  5. Logout Functionality

User Registration

The first step in creating an authentication system is to allow users to register. This involves collecting user data and storing it securely in a database. Below is an example of a simple user registration form and the corresponding PHP code to handle the registration process.

Registration Form

<form action="register.php" method="POST">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>
    
    <input type="submit" value="Register">
</form>

Registration Logic

<?php
// register.php
require 'database.php'; // Include your database connection

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Hash the password

    // Prepare and execute the SQL statement
    $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    if ($stmt->execute([$username, $password])) {
        echo "User registered successfully!";
    } else {
        echo "Error: " . $stmt->errorInfo()[2];
    }
}
?>

User Login

After registration, users need to log in to access the application. The login process involves verifying the user's credentials against the database.

Login Form

<form action="login.php" method="POST">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>
    
    <input type="submit" value="Login">
</form>

Login Logic

<?php
// login.php
require 'database.php'; // Include your database connection

session_start(); // Start the session

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

    // Prepare and execute the SQL statement
    $stmt = $pdo->prepare("SELECT password FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

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

Password Hashing

Using password_hash() and password_verify() functions is essential for securely storing and verifying passwords. These functions handle salting and hashing automatically, making them a best practice for password management.

FunctionDescription
password_hash()Creates a password hash using a strong one-way hashing algorithm.
password_verify()Verifies a password against a hashed value.

Session Management

Once a user is authenticated, you need to manage their session effectively. PHP's built-in session management can be utilized for this purpose.

Starting a Session

At the beginning of each page that requires authentication, ensure that the session is started:

<?php
session_start(); // Start the session
if (!isset($_SESSION['username'])) {
    header("Location: login.php"); // Redirect to login if not authenticated
    exit();
}
?>

Logout Functionality

Implementing a logout function is straightforward. It involves destroying the session and redirecting the user to the login page.

Logout Logic

<?php
// logout.php
session_start();
session_destroy(); // Destroy the session
header("Location: login.php"); // Redirect to login page
exit();
?>

Conclusion

In this tutorial, we have implemented a basic PHP authentication system that includes user registration, login, password hashing, session management, and logout functionality. By following these best practices, you can create a secure and efficient authentication system tailored to your application's needs.

Learn more with useful resources