What is a Session in PHP?

A session in PHP is a way to store user-specific information on the server across multiple pages (unlike cookies which are stored in the browser). It helps track user activity like login, cart items, or user preferences without exposing data to the client.

Why Use Sessions?

  • Store sensitive data securely (e.g., user_id, email)
  • Maintain login status
  • Track user behavior during a single visit

 

How PHP Sessions Work:

  1. PHP generates a unique Session ID for each user.

  2. That ID is sent to the browser via a cookie (PHPSESSID).

  3. PHP uses the ID to retrieve the session data stored on the server.

Start a Session:

login.php


session_start(); // Always put this at the top of your file

Set Session Data:

login.php


$_SESSION['username'] = 'John';

Get Session Data:

login.php


echo $_SESSION['username']; // Outputs: John

Destroy a Session:

logout.php


session_start();
session_unset();     // Remove all session variables
session_destroy();   // Destroy the session