How to implement a login system in PHP

How to Implement a Login System in PHP: A Comprehensive Guide

In the digital age, user authentication is a fundamental aspect of web development. A login system not only secures your application but also enhances user experience by personalizing interactions. This article dives into the step-by-step process of implementing a login system in PHP, providing clear code examples, actionable insights, and troubleshooting tips along the way.

Understanding the Basics of a Login System

A login system typically consists of two main components: the user interface (UI) and the backend logic that handles authentication. Users are required to enter their credentials (usually a username and password) to gain access to protected areas of your application.

Use Cases for a Login System

  • E-commerce Platforms: To manage user accounts, track orders, and maintain shopping carts.
  • Social Media Sites: To create personalized user experiences and manage user interactions.
  • Content Management Systems (CMS): To restrict access to certain content based on user roles.

Step 1: Setting Up Your Environment

Before diving into coding, ensure you have a local server environment set up. You can use tools like XAMPP, WAMP, or MAMP to create a local PHP environment.

Requirements:

  • PHP installed (preferably version 7.4 or higher)
  • MySQL database
  • A code editor (like Visual Studio Code or Sublime Text)

Step 2: Create the Database

To store user credentials securely, you will need a MySQL database. Follow these steps to create a database and a users table:

  1. Open your MySQL interface (e.g., phpMyAdmin).
  2. Create a new database called login_system.
  3. Execute the following SQL command to create a users table:
CREATE TABLE users (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
);

Step 3: Building the Registration System

Before users can log in, they must register. Here's a simple registration form in PHP:

Registration Form (register.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
</head>
<body>
    <form action="register.php" method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Register</button>
    </form>
</body>
</html>

Registration Logic

Add the following PHP code at the top of your register.php file to handle user registration:

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

    // Database connection
    $conn = new mysqli('localhost', 'root', '', 'login_system');

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Insert user into the database
    $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    $stmt->bind_param("ss", $username, $password);
    if ($stmt->execute()) {
        echo "Registration successful!";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();
}
?>

Step 4: Creating the Login Form

Now that users can register, let’s create a login form.

Login Form (login.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <form action="login.php" method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>
</body>
</html>

Login Logic

Add the following PHP code at the top of your login.php file to handle user authentication:

<?php
session_start(); // Start a new session

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

    // Database connection
    $conn = new mysqli('localhost', 'root', '', 'login_system');

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Fetch user from the database
    $stmt = $conn->prepare("SELECT password FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($hashed_password);
        $stmt->fetch();

        // Verify password
        if (password_verify($password, $hashed_password)) {
            $_SESSION['username'] = $username; // Set session variable
            echo "Login successful! Welcome, " . $username;
        } else {
            echo "Invalid password.";
        }
    } else {
        echo "Username not found.";
    }

    $stmt->close();
    $conn->close();
}
?>

Step 5: Logout Functionality

To allow users to log out, you can create a simple logout script.

Logout Script (logout.php)

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

Troubleshooting Common Issues

  1. Database Connection Errors: Ensure your database credentials are correct.
  2. Password Verification Issues: Make sure you are using password_hash() for registration and password_verify() for login.
  3. Session Issues: Check if session_start() is called at the beginning of your scripts.

Conclusion

Implementing a login system in PHP enhances the security and usability of your web applications. By following the steps outlined in this guide, you can create a basic but effective authentication system. Remember to always keep security in mind—use password hashing and secure your database connections. As you expand your web application, consider adding features like password reset functionality, email verification, and user role management for a more robust system. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.