πŸ“ Web Development

PHP Sessions: Login State and $_SESSION Explained

Aug 23, 20265 min read2 viewsBy Flow

PHP sessions let your site remember a visitor from one page to the next. HTTP forgets everything between requests, without sessions, a user who logs in on one page is a stranger again on the next.

Before going any further, to understand sessions I want All My Viewers to Know that every tutorial I have Posted so far was on XAMPP which is a Web Server for your personal computer/laptops it can behave like a web server online too if you do port forwarding but anyways that's another matter let's get back to sessions.

Why PHP sessions exist

Every request to your server arrives with no memory of the last one. That is not a flaw, it is how the web was designed. It is also why a shopping cart, a logged-in user or a "welcome back" message needs something extra.

Now PHP has a function named as "session_start()."Β  and here is what actually happens the moment you call session_start().

PHP creates a file on your server. On XAMPP you will find it sitting in C:\xampp\tmp with a name like sess_8f3a1c9d4b2e. Everything you put into $_SESSION gets written into that file.

Then PHP sends the browser one small thing: the name of that file. The browser stores it as a cookie called PHPSESSID.

On the next request the browser sends that cookie back. PHP reads the ID, finds the matching file, and loads it into $_SESSION. That is the whole mechanism β€” no magic in it.

So sessions and cookies are not two competing options. They work together:

  • The session is the file on the server, holding your data.
  • The cookie is the browser’s copy of that file’s name.

That is exactly why session data is safer than cookie data. A visitor can open their browser tools and read the cookie β€” but all they find is an ID. The values themselves never leave your server.

One caveat so this stays honest: files are just PHP’s default storage. Larger sites move sessions into Redis or a database instead. Same idea, different shelf.

Starting a session and storing something

<?php
session_start();

$_SESSION["username"] = "Ayesha";
$_SESSION["role"] = "student";

echo "Saved to the session.";
?>

Output:

PHP sessions output confirming a username and role were saved to $_SESSION

session_start() must run before any output β€” no HTML, no echo, not even a blank line before <?php. It sends a cookie header, and headers cannot go out after content has started.

After that $_SESSION behaves like any associative array from PHP arrays. The only difference is that it survives to the next page.

Reading it on another page

<?php
session_start();

if (isset($_SESSION["username"])) {
    echo "Welcome back, " . htmlspecialchars($_SESSION["username"]) . "<br>";
    echo "Role: " . htmlspecialchars($_SESSION["role"]);
} else {
    echo "No session found. Visit the first page.";
}
?>

Output:

PHP sessions read on a second page, printing Welcome back Ayesha and the role student

A different file, and the values are still there. That is the whole point of sessions.

session_start() is needed on every page that touches $_SESSION, not just the first. Forgetting it is the most common reason a session "stops working".

Note htmlspecialchars() again β€” same rule as PHP forms. Session data often came from a user in the first place, so escape it on the way out.

A tiny login gate

This is the pattern behind almost every members area you have used.

<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $user = trim($_POST["user"] ?? "");
    $pass = trim($_POST["pass"] ?? "");

    if ($user === "ayesha" && $pass === "secret123") {
        session_regenerate_id(true);
        $_SESSION["username"] = $user;
        echo "Logged in as " . htmlspecialchars($user);
    } else {
        echo "Wrong details.";
    }
}
?>


    User: 
Pass:
Log in

Output:

PHP sessions login gate output showing a successful log in as ayesha

session_regenerate_id(true) is there on purpose. It issues a fresh session ID the moment someone logs in, so a ticket handed out before login cannot be reused afterwards. One line, and it closes a real hole called session fixation.

To be clear about this example: the username and password are hard-coded so the lesson stays about sessions. A real login checks a database and stores a hash made with password_hash() β€” never the password itself.

Protecting a page

<?php
session_start();

if (!isset($_SESSION["username"])) {
    echo "You must log in first.";
    exit;
}

echo "Secret dashboard for " . htmlspecialchars($_SESSION["username"]);
?>

Output:

PHP sessions protected page showing the dashboard only because a session exists

exit is doing real work here. Without it the rest of the page keeps running and prints anyway β€” the check would look right and protect nothing.

Logging out properly

<?php
session_start();

$_SESSION = [];
session_destroy();

echo "Logged out.";
?>

Output:

PHP sessions logout output after clearing $_SESSION and destroying the session

Two steps, and both matter. $_SESSION = [] empties the data for the current request; session_destroy() removes the session on the server. Doing only one leaves half the door open.

So when do I use a cookie instead?

Now that the mechanism is clear, the choice is simple.

Use a session for anything the visitor must not be able to change β€” who they are, what they are allowed to do, what is in their cart.

Use a cookie on its own for small preferences where it would not matter if someone edited it: a dark-mode setting, a chosen language, a dismissed banner.

A quick test: if changing the value would let someone become another user, it belongs in the session.

Three mistakes with PHP sessions

Output before session_start(). One space before <?php is enough to trigger "headers already sent". Check the very top of the file first.

Forgetting session_start() on later pages. $_SESSION comes back empty and everything looks broken for no visible reason.

Trusting session data blindly. It is safer than a cookie, but it usually started as user input. Escape it when you print it.

Common questions about PHP sessions

The questions that come up most often once a login screen enters the picture.

What is the difference between a session and a cookie in PHP?

A session keeps the data on the server and gives the browser only an ID. A cookie stores the actual value in the browser, where the visitor can read and change it. Anything security-related belongs in the session.

How do I fix "headers already sent" when starting a session?

Something was printed before session_start() ran. Look for HTML above the PHP block, an echo, or a stray blank line or space before <?php at the very top of the file.

Why is my $_SESSION empty on the next page?

Almost always a missing session_start() on that page. Every file that reads or writes $_SESSION needs it, and it must run before any output.

How long does a PHP session last?

Until the browser closes, or until the server clears it β€” around 24 minutes of inactivity by default on most setups. Both are configurable, and neither should be treated as exact.

Is it safe to store a user ID in a PHP session?

Yes, that is exactly what sessions are for β€” the value never leaves the server. Storing it in a plain cookie would not be safe, because anyone could edit it and become another user.

What is next

You can now read what a visitor types and remember who they are between pages. That is the web plumbing done.

The next lesson steps away from the browser and looks at how you arrange the code itself β€” grouping data and behaviour into objects. That is PHP OOP, and it is what the database lesson after it is written in.

Need a refresher on reading input safely? Go back through PHP forms.

Comments

Loading comments...

Link copied to clipboard