How to Use PHP Sessions: Complete Guide with a Login Example

PHP sessions let your website remember a user from one page to the next โ€” login state, shopping carts, flash messages. This guide explains how sessions really work, builds a complete login example with MySQL, and covers the security steps most tutorials skip.

RH Raja HunainAuthor 29 Nov 2026 3 min read 8 views
Table of Contents
Share

HTTP forgets everything. Every time a browser asks your server for a page, it is a brand-new conversation: the server has no memory of the previous request and no way to know that the person who just logged in is the same person now asking for the dashboard. This is by design โ€” it keeps the web fast and simple โ€” but anything your site needs to remember across pages has to be stored somewhere on purpose.

That is exactly what PHP sessions are for. A session gives each visitor a private storage box on the server, keyed by a random ID that the browser carries in a cookie. You put the user ID in the box when they log in, and on every later page you open the box and check what is inside. Shopping carts, login state, flash messages, multi-step forms โ€” all of these are sessions doing their job quietly in the background.

In this tutorial you will learn how to use PHP sessions properly: how they work, how to start one, a complete login example backed by MySQL, how to protect pages and log users out cleanly, and the security settings that separate a working session from a safe one.

How PHP sessions actually work

A session has two halves, and understanding both explains almost every session bug you will ever meet.

The first half lives in the browser: a small cookie called PHPSESSID that holds nothing but a random session ID. The second half lives on the server: a file (by default, in the server's temporary directory) named after that ID, holding the actual data. The browser never sees your data; it only carries the key. The server never trusts the browser's word about who the user is; it only trusts what it finds in its own file under that key.

The flow goes like this. The visitor loads a page, and your code calls session_start(). PHP reads the session ID from the visitor's cookie โ€” or creates a new one if there is no cookie yet โ€” loads the matching data file, and fills the $_SESSION superglobal array with whatever it contains. Your code reads and writes $_SESSION like any other array. When the script ends, PHP writes the array back to the file automatically. On the next page, the same cookie arrives, the same file loads, and the data is still there.

That is the whole mechanism. Everything else โ€” login, logout, timeouts, security โ€” is just code you write on top of it.

Step 1: Start a session and store data

Every page that needs session data must call session_start() first, and it must be called before any output โ€” no HTML, no echo, not even a blank line before the opening <?php tag. The reason is that session_start() sends the session cookie as an HTTP header, and headers cannot be sent after the body has started. If you get this wrong, PHP warns you with the classic "headers already sent" error, which How to Fix 'Headers Already Sent' Error in PHP explains in detail.

<?php
// Always the very first line โ€” before any output.
session_start();

// Store values in the session, like any array.
$_SESSION['user_id'] = 42;
$_SESSION['username'] = 'ada';
$_SESSION['cart'] = ['SKU-1', 'SKU-2'];

// Read them back on this page or any later page.
echo 'Logged in as ' . $_SESSION['username'];

To check whether a value exists before reading it, use isset() or the null coalescing operator, exactly as you would with any array. Reading a key that was never set produces a warning in PHP 8, so never assume a key is there:

<?php
session_start();

$username = $_SESSION['username'] ?? 'guest';

if (isset($_SESSION['user_id'])) {
    echo 'Welcome back, ' . htmlspecialchars($_SESSION['username']);
} else {
    echo 'You are not logged in.';
}

Step 2: A complete login example with MySQL

This is the pattern most people search for: a login form, a handler that checks the password against a MySQL database, a protected page, and a logout. The example uses PDO with prepared statements and password_verify(), because a login that stores plain-text passwords or builds SQL from raw input is worse than no login at all.

First, the login handler. It verifies the credentials, and only on success does it write to the session โ€” and the first thing it does after that is regenerate the session ID, which is explained in the security section below:

<?php
// login.php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pdo = new PDO(
        'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
        'app_user',
        'your-strong-password'
    );

    $stmt = $pdo->prepare('SELECT id, username, password_hash FROM users WHERE username = ?');
    $stmt->execute([$_POST['username']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($_POST['password'], $user['password_hash'])) {
        // New session ID after login โ€” stops session fixation attacks.
        session_regenerate_id(true);

        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['logged_in_at'] = time();

        header('Location: dashboard.php');
        exit;
    }

    $error = 'Invalid username or password.';
}
?>

<?php if (!empty($error)): ?>
    <p><?= htmlspecialchars($error) ?></p>
<?php endif; ?>

<form method="post">
    <label>Username <input type="text" name="username" required></label>
    <label>Password <input type="password" name="password" required></label>
    <button type="submit">Log in</button>
</form>

The matching registration step is password_hash($_POST['password'], PASSWORD_DEFAULT) when the account is created โ€” never store the password itself, only its hash.

Step 3: Protect a page with the session

A protected page is just a page that checks the session before showing anything. Put the check at the very top, before any HTML, and redirect visitors who are not logged in. One small file included at the top of every protected page keeps this consistent across the whole site:

<?php
// auth.php โ€” include this at the top of every protected page.
session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
<?php
// dashboard.php
require 'auth.php';
?>
<h1>Welcome, <?= htmlspecialchars($_SESSION['username']) ?></h1>
<p><a href="logout.php">Log out</a></p>

Step 4: Log out properly

Logging out is not just deleting one key. A half-finished logout leaves the session file and cookie alive, and the next visitor on a shared computer can simply go back to the dashboard. Do all three steps: clear the array, delete the cookie, and destroy the session on the server:

<?php
// logout.php
session_start();

// 1. Empty the session data.
$_SESSION = [];

// 2. Delete the session cookie from the browser.
if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(),
        '',
        time() - 42000,
        $params['path'],
        $params['domain'],
        $params['secure'],
        $params['httponly']
    );
}

// 3. Destroy the session on the server.
session_destroy();

header('Location: login.php');
exit;

To remove a single value without logging the user out โ€” for example, emptying a cart after checkout โ€” use unset($_SESSION['cart']). The rest of the session stays untouched.

Step 5: Make the session secure

A session that works is not the same as a session that is safe. These are the settings that matter most.

Regenerate the ID on login. session_regenerate_id(true) gives the user a fresh session ID the moment they authenticate, and the true argument deletes the old session file. Without this, an attacker who somehow learned the pre-login session ID can ride it straight into the logged-in account โ€” a session fixation attack.

Lock the cookie down. Configure the session cookie before session_start() so JavaScript cannot read it, it is only sent over HTTPS, and other sites cannot trigger it in cross-site requests:

<?php
session_start([
    'cookie_httponly' => true,   // JavaScript cannot read the cookie.
    'cookie_secure'   => true,   // Only sent over HTTPS (enable on live sites).
    'cookie_samesite' => 'Lax',  // Not sent on cross-site POST requests.
    'use_strict_mode' => true,   // Reject session IDs the server never issued.
]);

Add an idle timeout. Sessions do not expire just because the user walked away. Store the last activity time and check it on every protected page:

<?php
session_start();

$timeout = 30 * 60; // 30 minutes of inactivity.

if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $timeout)) {
    session_destroy();
    header('Location: login.php');
    exit;
}

$_SESSION['last_activity'] = time();

Store as little as possible. Keep the user ID and a display name in the session โ€” never a password or a password hash. If you need fresh details, look them up from the database with the stored user ID.

Sessions vs cookies vs tokens

A cookie is just storage in the browser โ€” the user can see it and change it, so never put anything sensitive or trusted in one. A session is server-side storage with only an ID in a cookie, which is why it is the right tool for login state in a classic PHP site.

Tokens belong to a different architecture. If your front end is a separate JavaScript app calling an API, there is no PHP page rendering the session for you, and a token (usually sent as a Bearer header) is the standard way to authenticate each request. How to Create a REST API in Laravel 13 shows that pattern with Sanctum.

Common mistakes that break sessions

Output before session_start(). Even a single space before <?php, a UTF-8 BOM at the start of the file, or an echo in an included file will break it. Keep session_start() on the first line of the file, and save your PHP files without a BOM.

Forgetting session_start() on one page. Each page is independent. A dashboard that never calls session_start() sees an empty $_SESSION and redirects a logged-in user back to the login page, even though the session is perfectly fine. If the login works and the next page forgets you, this is the first thing to check.

Code running after a redirect. Code after header('Location: ...') still runs unless you call exit. Always exit immediately after a redirect header, or the lines below it can overwrite the session data you just set.

Expecting the session to survive a domain change. The session cookie belongs to one domain. Moving from example.com to www.example.com โ€” or from localhost to 127.0.0.1 โ€” starts a brand-new session, because the browser treats those as different sites.

Frequently asked questions

Why is my session empty on the next page? Almost always one of two things: the second page never called session_start(), or the first page sent output before session_start() and the cookie was never set. Check both pages, and check the browser's cookies to see whether PHPSESSID is actually there.

How long does a PHP session last? By default, until the browser closes or the server's garbage collection removes the idle session file โ€” usually after 24 minutes of inactivity (session.gc_maxlifetime, 1440 seconds).

What is the difference between session_unset() and session_destroy()? session_unset() clears the $_SESSION array but leaves the session itself alive; session_destroy() deletes the session data on the server. For a logout, use both โ€” clear the array, delete the cookie, and destroy the session, as shown above.

Can I store an object or an array in a session? Yes โ€” arrays work directly, and objects work as long as the class is defined before session_start() runs on the next page. Store IDs and plain arrays when you can; look the objects up fresh from the database when you need them.

Conclusion

PHP sessions solve the web's memory problem with a simple idea: a random ID in a cookie, and the real data kept safely on the server. Start the session before any output, store only what you need in $_SESSION, protect pages with a single check at the top, and log users out by clearing the data, deleting the cookie, and destroying the session. Then add the security steps โ€” regenerate the ID on login, lock the cookie down, and time out idle sessions.

#PHP #Sessions #Login #PHP8 #WebDevelopment #MySQL #Security #ProgrammingTips

Was this helpful? 0 likes Login to like & bookmark
RH

Written by

Raja Hunain

Full Stack Developer at Raja Dev Solutions โ€” writes about real development work, the errors he faced and exactly how he fixed them, plus practical Laravel, PHP, JavaScript and MySQL tutorials.

More about the author

Comments (0)

No comments yet. Be the first to comment.

Leave a comment

Comments are moderated and appear after approval.

Keep reading

Related Articles

Error & Fix PHP Development 28 Nov 2026 ยท 3 min read

How to Fix 'Allowed Memory Size Exhausted' Error in PHP

Your PHP script dies with "Allowed memory size of 134217728 bytes exhausted" โ€” and raising the limit only buys you time. This guide shows how to read the three numbers in the message, find the limit that actually applies to your runtime, raise it in the right place, and then fix the code that eats the memory in the first place: generators, chunked queries, and streaming file reads.

How to Fix "Headers Already Sent" Error in PHP
Error & Fix PHP Development 22 Nov 2026 ยท 2 min read

How to Fix "Headers Already Sent" Error in PHP

PHP says "Cannot modify header information - headers already sent" when output reaches the browser before your header() call. Here is how to read the message, find the exact line that sent output, and fix it for good.