how-to-implement-a-basic-login-system-in-php.html

How to Implement a Basic Login System in PHP

In the world of web development, creating a secure login system is one of the fundamental tasks you will encounter. A robust login system not only protects sensitive user information but also enhances user experience. In this article, we will guide you through the process of implementing a basic login system in PHP, covering everything from user registration to session management.

Understanding the Basics

Before diving into the code, let's clarify what a login system entails. A login system typically involves:

  • User Registration: Allowing users to create accounts.
  • User Login: Enabling users to authenticate themselves.
  • Session Management: Maintaining user sessions to keep them logged in.

Use Cases for a Login System

A login system is essential for various applications, including:

  • E-commerce Sites: To manage user accounts and orders.
  • Social Media Platforms: To connect users and manage profiles.
  • Content Management Systems: To restrict access to certain sections of the site.

Setting Up Your Environment

To implement a login system in PHP, you'll need:

  • A web server (like Apache or Nginx).
  • PHP installed (version 7.0 or higher is recommended).
  • A database server (MySQL or MariaDB).

Step 1: Create the Database

First, let's create a MySQL database to store user data. You can use the following SQL command:

CREATE DATABASE user_management;

USE user_management;

CREATE TABLE users (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step 2: User Registration

Next, we need a form for user registration. Create a file named register.php and add the following code:

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

    // Database connection
    $conn = new mysqli("localhost", "root", "", "user_management");

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

    // Insert user into database
    $sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";

    if ($conn->query($sql) === TRUE) {
        echo "Registration successful!";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register</title>
</head>
<body>
    <h2>User Registration</h2>
    <form method="post">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Register">
    </form>
</body>
</html>

Step 3: User Login

Now, let’s create the login form. Create a file named login.php:

<?php
session_start(); // Start session

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

    // Database connection
    $conn = new mysqli("localhost", "root", "", "user_management");

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

    // Fetch user data
    $sql = "SELECT * FROM users WHERE username='$username'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if (password_verify($password, $row['password'])) {
            // Password is correct; set session variables
            $_SESSION['username'] = $username;
            echo "Login successful! Welcome, " . $_SESSION['username'];
        } else {
            echo "Invalid password!";
        }
    } else {
        echo "No user found with that username!";
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h2>User Login</h2>
    <form method="post">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Login">
    </form>
</body>
</html>

Step 4: Session Management

To manage user sessions, we need to create a file named dashboard.php where logged-in users can access their account:

<?php
session_start();

if (!isset($_SESSION['username'])) {
    header('Location: login.php'); // Redirect to login if not logged in
    exit;
}

echo "Welcome to your dashboard, " . $_SESSION['username'];
?>

<a href="logout.php">Logout</a>

Step 5: Logging Out

Finally, create a logout.php file to allow users to log out:

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

Troubleshooting Common Issues

When implementing a login system, you may encounter issues such as:

  • Error establishing a database connection: Ensure your database credentials are correct.
  • Password verification fails: Confirm you are using the same hashing algorithm for both registration and login.
  • Session not starting: Use session_start() at the beginning of your PHP files.

Conclusion

Implementing a basic login system in PHP is a crucial skill for any web developer. With the above steps, you’ve created a simple yet effective login system that handles user registration, login, session management, and logout functionality.

As you advance, consider adding features like password recovery, email verification, and enhanced security measures to protect user data. 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.