Login System | PHP Tutorial - Learn with VOKS
Back Next

Login System


What Is a Login System?

Simple Meaning

A login system allows users to:

  • create an account
  • log in with their email/username and password
  • access protected pages
  • stay logged in
  • log out

It is used in:

  • social media
  • e-commerce sites
  • school portals
  • admin dashboards

Technologies Used

| Technology | Purpose                                  |
|------------|------------------------------------------|
| PHP        | Handles form processing & authentication |
| MySQL      | Stores user data                         |
| HTML       | Creates the login form                   |
| CSS        | Styles the form                          |
| Sessions   | Keeps the user logged in                 |
| XAMPP/WAMP | Local development server                 |

How a Login System Works (Step-by-Step)

1️⃣ User Enters Login Details

User types:

  • email/username
  • password

into a form.

2️⃣ PHP Receives the Data

The form sends data to a PHP file using:

method="POST"

3️⃣ PHP Checks the Database

PHP:

  • connects to MySQL
  • searches for the user
  • verifies the password

4️⃣ If Correct → Create Session

Session stores:

$_SESSION["user_id"]

This means:

✅ user is logged in

5️⃣ Redirect to Dashboard

User is taken to:

dashboard.php

6️⃣ Logout Destroys Session

session_destroy();

User becomes logged out.

Database Structure

You need a users table.

| Column Name | Purpose                      |
|-------------|------------------------------|
| id          | Unique user ID               |
| username    | User’s name                  |
| email       | User’s email                 |
| password    | Hashed password              |
| created_at  | Registration date            |

VERY IMPORTANT: Password Hashing

❌ Never store plain passwords.

Use:

password_hash()

and

password_verify()

Complete System Flow

| Step | What Happens                          |
|------|----------------------------------------|
| 1    | User registers                        |
| 2    | Password is hashed                    |
| 3    | Data stored in database               |
| 4    | User logs in                          |
| 5    | PHP verifies password                 |
| 6    | Session is created                    |
| 7    | User accesses protected pages         |
| 8    | User logs out                         |

Basic File Structure

| File Name        | Purpose                    |
|------------------|----------------------------|
| register.php     | User signup logic          |
| login.php        | Login form & processing    |
| dashboard.php    | Protected page             |
| logout.php       | Ends session               |
| config.php       | Database connection        |

Database Connection (config.php)

$conn = new mysqli("localhost", "root", "", "test_db");

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

Simple Login Form (HTML)

<form method="POST" action="login.php">
  <input type="email" name="email" placeholder="Enter email" required>
  <input type="password" name="password" placeholder="Enter password" required>
  <button type="submit">Login</button>
</form>

Login Logic (PHP)

1️⃣ Start session

session_start();

2️⃣ Get form data

$email = $_POST['email'];
$password = $_POST['password'];

3️⃣ Find user

$sql = "SELECT * FROM users WHERE email='$email'";

4️⃣ Verify password

password_verify($password, $row['password']);

5️⃣ Create session

$_SESSION["user_id"] = $row["id"];

Protecting Pages

At the top of dashboard.php:

session_start();

if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();
}

This stops unauthorized users ❌

Logout System

session_start();
session_destroy();
header("Location: login.php");

Common Beginner Mistakes

| Mistake                      | Why It’s a Problem                | Fix                                      |
|------------------------------|-----------------------------------|------------------------------------------|
| Storing plain passwords      | Very insecure                     | Use password_hash()                      |
| Not using sessions           | User won’t stay logged in         | Use $_SESSION                            |
| No input validation          | SQL injection risk                | Use prepared statements                  |
| No page protection           | Anyone can access dashboard       | Check session before loading page        |

Basic Security

| Practice                     | Why It Matters                    |
|-------------------------------|-----------------------------------|
| Password hashing              | Protects user accounts            |
| Prepared statements           | Prevents SQL injection            |
| Session checks                | Secures private pages             |
| Input validation              | Prevents malicious data           |
| HTTPS                         | Encrypts login data               |

How To Run the Project (Step-by-Step)

1️⃣ Start XAMPP / WAMP

Start:

  • Apache
  • MySQL

2️⃣ Move Project Folder

Put the folder inside:

htdocs

Example:

C:\xampp\htdocs\login-system

3️⃣ Import Database

Go to:

http://localhost/phpmyadmin

Create database → run the SQL table query.

4️⃣ Open in Browser

http://localhost/login-system/register.php

How To Test

  1. Register a new user
  2. Go to login page
  3. Login
  4. Access dashboard
  5. Logout


Example Code:
//1. Project Folder Structure

login-system/
│── config.php
│── register.php
│── login.php
│── dashboard.php
│── logout.php

//2. Database Setup

Create Database
CREATE DATABASE login_system;
Create Users Table
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);


//3. config.php (Database Connection)

<?php
$host = "localhost";
$user = "root";
$pass = "";
$db   = "login_system";

$conn = new mysqli($host, $user, $pass, $db);

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


//4. register.php (User Registration)

<?php
session_start();
require 'config.php';

if (isset($_POST['register'])) {

    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

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

    if ($stmt->execute()) {
        echo "Registration successful. <a href='login.php'>Login here</a>";
    } else {
        echo "Error: " . $stmt->error;
    }
}
?>

<h2>Register</h2>
<form method="POST">
    <input type="text" name="username" placeholder="Username" required><br><br>
    <input type="email" name="email" placeholder="Email" required><br><br>
    <input type="password" name="password" placeholder="Password" required><br><br>
    <button name="register">Register</button>
</form>


//5. login.php (User Login)

<?php
session_start();
require 'config.php';

if (isset($_POST['login'])) {

    $email = $_POST['email'];
    $password = $_POST['password'];

    $stmt = $conn->prepare("SELECT id, password FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {

        $stmt->bind_result($id, $hashed_password);
        $stmt->fetch();

        if (password_verify($password, $hashed_password)) {
            $_SESSION['user_id'] = $id;
            header("Location: dashboard.php");
            exit();
        } else {
            echo "Invalid password";
        }

    } else {
        echo "No user found";
    }
}
?>

<h2>Login</h2>
<form method="POST">
    <input type="email" name="email" placeholder="Email" required><br><br>
    <input type="password" name="password" placeholder="Password" required><br><br>
    <button name="login">Login</button>
</form>


//6. dashboard.php (Protected Page)

<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
?>

<h2>Welcome to the Dashboard 🎉</h2>
<a href="logout.php">Logout</a>


//7. logout.php

<?php
session_start();
session_destroy();
header("Location: login.php");
exit();
PHP
Introduction PHP Configuration PHP CRUD (Create, Read, Update, Delete) PHP Error Handling PHP Form Submission Login System PHP Comments
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL