PHP + MYSQL + SESSION

Login & Logout System

Learn how to build a secure PHP authentication system with registration, login, sessions and logout.

What Are We Building?

We are going to create a simple user authentication system. A user can create an account, log in with their email and password, access a protected dashboard, and finally log out.


Passwords will not be stored as plain text. PHP's password_hash() and password_verify() functions will be used.

Project Flow

Register
→
Database
→
Login
→
Session
→
Dashboard
→
Logout

Step 1 — Create the Project Folder

login-system/

Create these files:

login-system/
│
├── tutorial.php
├── index.php
├── register.php
├── login.php
├── dashboard.php
├── logout.php
└── style.css

Step 2 — Create the Users Table

Select the aifa_php_lab database in phpMyAdmin and run:

CREATE TABLE IF NOT EXISTS users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    full_name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step 3 — Create the Registration Form

The registration form collects:

Full Name
Email Address
Password

The form sends information to register.php.

<form action="register.php" method="POST">

Step 4 — Hash the Password

Never store a user's password directly in the database. Use password_hash().

$hashedPassword = password_hash(
    $password,
    PASSWORD_DEFAULT
);

The database stores the generated hash instead of the original password.

Step 5 — Login Verification

When the user logs in, PHP finds the account by email and verifies the entered password.

$result = $stmt->get_result();

$user = $result->fetch_assoc();

if (
    $user &&
    password_verify(
        $password,
        $user['password']
    )
) {

    // Login successful

}

Step 6 — Create a Session

After successful login, we use a PHP session to remember that the user is authenticated.

session_start();

$_SESSION['user_id'] = $user['id'];

$_SESSION['user_name'] = $user['full_name'];

$_SESSION['user_email'] = $user['email'];

Step 7 — Protect the Dashboard

The dashboard should not be accessible to users who have not logged in.

session_start();

if (!isset($_SESSION['user_id'])) {

    header("Location: index.php");

    exit;

}

Step 8 — Logout

When the user clicks Logout, we destroy the session.

session_start();

session_unset();

session_destroy();

header("Location: index.php");

exit;

Important Security Rules

Never store plain-text passwords.
Use password_hash().
Use password_verify().
Use prepared statements.
Protect private pages using sessions.
Destroy sessions during logout.

Practice Questions

Add a phone number to registration.
Add a confirm password field.
Add a remember-me checkbox.
Create a profile page.
Display the user's registration date.

Ready to See the Complete Project?

You have learned how PHP authentication works. Now open the complete working project.

🚀 Run Complete Project