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 visitPHP generates a unique session ID and sends it to the browser as a cookie (usually named PHPSESSID).
2. Server storageWhatever you put in $_SESSION is saved on the server, keyed by that session ID.
3. Later visitsThe browser sends the same cookie back, PHP loads that visitor's $_SESSION data automatically.
4. EndingThe 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>...
Common mistake: Calling 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

4.1 Remove one key
<?php
  unset($_SESSION['cart_count']); // only removes this one key
?>
4.2 Destroy the whole session
<?php
  $_SESSION = [];       // clear the array first
  session_destroy(); // then remove the server-side session data
?>
Note: After 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:

SessionsCookies
Data lives on the serverData 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 practiceLimited 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.

You've viewed this page 1 time this session.

7) Best Practices & Common Mistakes

IssueProblemFix
Calling session_start() late"Headers already sent" warning, session may not persistPut it at the very top of the file, before any output
Storing large objects in $_SESSIONSlows every request for that visitorStore only small identifiers (IDs), fetch details from a DB when needed
Trusting session data blindly for authorizationStale/forged roles if not re-checkedRe-validate critical permissions against the database
Forgetting to regenerate the session ID after loginSession fixation riskCall session_regenerate_id(true) right after a successful login

8) Practice Tasks

  1. Build a simple "logged in as" banner: store a name in $_SESSION on a form submit, show it on every page, and add a "Log out" button that calls session_destroy().
  2. Add a shopping-cart item counter using $_SESSION['cart'] as an array.
  3. Store a "last visited page" value in the session and display it as "Welcome back, you last viewed: ...".
  4. Research and try session_regenerate_id() — why is it useful right after login?
Next: Continue with Cookies — store small bits of data directly in the visitor's browser.