Managing State with Superglobals: PHP Sessions and $_SERVER
Learn how to persist user data across requests using PHP sessions and access server environment information with the $_SERVER superglobal.

Previously in this course, we covered sanitization and validation to ensure that data coming from users is safe to process. Now that we can handle user input securely, we need a way to remember that user across different pages of our application.
Because HTTP is stateless—meaning the server "forgets" who you are the moment a request finishes—we need a mechanism to persist data. Enter PHP sessions and the $_SERVER superglobal.
Understanding State Management
In a web context, "state" refers to the current information about a user's interaction with your app (e.g., "Is this user logged in?", "What is in their shopping cart?"). Since PHP scripts execute and then terminate, we use PHP sessions to store this data on the server, associating it with a unique ID sent to the browser via a cookie.
Starting a Session
Before you can interact with session data, you must explicitly initialize the session. You do this with the session_start() function.
PHP<?php #6A9955">// Must be called before any output is sent to the browser session_start(); #6A9955">// We can now access the $_SESSION superglobal $_SESSION['user_id'] = 42; $_SESSION['username'] = 'dev_user'; ?>
The $_SESSION superglobal is an associative array. Any value you store here remains available on every page load as long as the user's session remains active.
Reading and Destroying Data
To retrieve data on another page, simply call session_start() again, and the $_SESSION array will be populated with the data you saved previously.
PHPsession_start(); if (isset($_SESSION['username'])) { echo "Welcome back, " . htmlspecialchars($_SESSION['username']); }
When a user logs out, you should clean up their session data:
PHPsession_start(); session_unset(); #6A9955">// Removes all variables session_destroy(); #6A9955">// Destroys the session file on the server
Inspecting Environment Info with $_SERVER

While sessions handle user-specific state, the $_SERVER superglobal provides metadata about the server environment, the current request, and the script being executed. It is populated by the web server (like Apache or Nginx).
Commonly used keys include:
$_SERVER['REQUEST_METHOD']: Tells you if the request was aGETorPOST.$_SERVER['REQUEST_URI']: The path currently being accessed.$_SERVER['REMOTE_ADDR']: The IP address of the user.
Worked Example: Tracking Request Info
Let’s update our MVC project entry point to log some basic request information.
PHP#6A9955">// public/index.php session_start(); #6A9955">// Track visit count in the session $_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1; echo "Page: " . $_SERVER['REQUEST_URI'] . "<br>"; echo "Method: " . $_SERVER['REQUEST_METHOD'] . "<br>"; echo "Visit count: " . $_SESSION['visits'];
Hands-on Exercise
- Create a file named
counter.php. - Start a session and use
$_SESSIONto increment a counter every time the page refreshes. - Display the user's IP address using
$_SERVER['REMOTE_ADDR']. - Add a button that links to a
clear.phpfile, which destroys the session and redirects the user back tocounter.php.
Common Pitfalls
- Output before
session_start(): If youechotext or send HTML before callingsession_start(), you will trigger a "Headers already sent" error. Always putsession_start()at the very top of your script. - Trusting
$_SERVERblindly: Never trust$_SERVER['HTTP_USER_AGENT']or other headers for security-critical logic, as they are easily spoofed by malicious clients. - Session Lifetime: Sessions don't last forever. Depending on server configuration, they may time out after a period of inactivity.
FAQ
Q: Where is session data actually stored? A: By default, PHP stores session data in temporary files on the server's filesystem.
Q: Can I store objects in $_SESSION?
A: Yes, but you must ensure the class definition is included before session_start() on every page, or PHP will fail to reconstruct the object (it will become incomplete).
Q: Why is $_SERVER empty?
A: If you are running your script from the CLI, the web-server-related keys (like REQUEST_URI) will not exist. $_SERVER is populated by the web server interface.
Recap
We've learned that PHP sessions allow us to maintain state across stateless HTTP requests, while the $_SERVER superglobal grants us access to vital request and server metadata. By combining these, you can build personalized experiences where the application "remembers" the user as they navigate through your MVC project.
Up next: We will explore how to perform clean redirects and manage HTTP status codes to control the user's navigation flow.
Work with me

Laravel REST API Development
Clean, secure, well-documented Laravel REST APIs — the backend engine for your app, mobile client, or SaaS. Built by an API specialist.

FilamentPHP Admin Panel & Dashboard Development
A powerful admin panel for your Laravel app — built with FilamentPHP so you can manage everything without touching the database.


