Sessions
A session lets your server remember information about a visitor across multiple page loads, without storing that data in the URL or asking the visitor to log in on every request. The data itself lives on the server; the browser only holds a small cookie containing a random session ID that points back to it.
1) How a Session Works
| 1. First visit | PHP generates a unique session ID and sends it to the browser as a cookie (usually named PHPSESSID). |
|---|---|
| 2. Server storage | Whatever you put in $_SESSION is saved on the server, keyed by that session ID. |
| 3. Later visits | The browser sends the same cookie back, PHP loads that visitor's $_SESSION data automatically. |
| 4. Ending | The session data is cleared when you call session_destroy(), or when it naturally expires on the server. |
2) Starting a Session
session_start() must run before any HTML or other output — it needs to
send a cookie header, and headers can only be sent before anything else is printed. That's why it
always sits at the very top of a PHP file, above the <!DOCTYPE html>.
<?php
session_start(); // must be first, before any echo/HTML
?>
<!DOCTYPE html>
<html>...
session_start() after some HTML (even
a blank line before <?php) triggers a "headers already sent" warning and the
session may silently fail to start.3) Storing & Reading Session Data
<?php
session_start();
// Store data
$_SESSION['username'] = 'sonu';
$_SESSION['cart_count'] = 3;
?>
<?php
// On a LATER page load / different page (session_start() called first)
session_start();
echo "Welcome back, " . ($_SESSION['username'] ?? 'guest');
?>
4) Removing Data
<?php
unset($_SESSION['cart_count']); // only removes this one key
?>
<?php
$_SESSION = []; // clear the array first
session_destroy(); // then remove the server-side session data
?>
session_destroy(), redirect the visitor (PRG
pattern) instead of continuing to output HTML in the same request — that avoids using a
half-destroyed session on the current page.5) Sessions vs Cookies (Quick Preview)
Sessions store data on the server; cookies store data in the browser. The next page, Cookies, covers the full comparison — for now, the short version:
| Sessions | Cookies |
|---|---|
| Data lives on the server | Data lives in the visitor's browser |
| Ends when the browser/session closes (by default) | Can persist for days/months if given an expiry |
| Not size-limited in practice | Limited to about 4KB per cookie |
6) Working Demo: Live Visit Counter
Every time this exact page loads, the server increments
$_SESSION['php_tutorial_visits'] and shows you the new count. Reload the page a few
times to watch it climb, then click Reset Session to call session_destroy()
and start over at zero.
7) Best Practices & Common Mistakes
| Issue | Problem | Fix |
|---|---|---|
Calling session_start() late | "Headers already sent" warning, session may not persist | Put it at the very top of the file, before any output |
Storing large objects in $_SESSION | Slows every request for that visitor | Store only small identifiers (IDs), fetch details from a DB when needed |
| Trusting session data blindly for authorization | Stale/forged roles if not re-checked | Re-validate critical permissions against the database |
| Forgetting to regenerate the session ID after login | Session fixation risk | Call session_regenerate_id(true) right after a successful login |
8) Practice Tasks
- Build a simple "logged in as" banner: store a name in
$_SESSIONon a form submit, show it on every page, and add a "Log out" button that callssession_destroy(). - Add a shopping-cart item counter using
$_SESSION['cart']as an array. - Store a "last visited page" value in the session and display it as "Welcome back, you last viewed: ...".
- Research and try
session_regenerate_id()— why is it useful right after login?