PHP ยท Chapter 32 of 44

PHP Sessions

Sessions let you store user data on the server across multiple page requests, identified by a unique session ID usually stored in a cookie on the client. Sessions are commonly used to keep users logged in as they navigate a site.

Unlike cookies, session data is stored on the server, making it more secure for sensitive information like user IDs or roles. Every page that uses sessions must call session_start() before any output is sent.

Syntax
session_start();
$_SESSION["key"] = "value";

Starting a session

session_start() must be called at the very top of every script that uses session data, before any HTML or whitespace is output.

Storing and destroying session data

Data is stored in the $_SESSION array, like $_SESSION["user"] = "Amy";. session_destroy() ends the session and clears all its data.

Example 1 (php)
<?php
  session_start();
  $_SESSION["username"] = "Amy";
  echo "Session started for " . $_SESSION["username"];
?>
Output
Session started for Amy

The username is stored in the session so it can be accessed on later pages.

Example 2 (php)
<?php
  session_start();
  echo isset($_SESSION["username"]) ? $_SESSION["username"] : "Not logged in";
?>
Output
Amy

On a later page, the same session data is still available after calling session_start().

Key points

  • session_start() must run before any output on every page using sessions.
  • Session data is stored in the $_SESSION array.
  • Sessions store data on the server, unlike cookies which store data on the client.
  • session_destroy() ends a session and clears its data.
๐Ÿ’ก Note: Always regenerate the session ID with session_regenerate_id() after login to help prevent session fixation attacks.

๐Ÿ“ Quick Quiz

1. What must be called before using sessions on a page?

2. Where is session data primarily stored?

3. Which function ends a session and clears its data?