Unlike Cookies, which store data on the user’s browser, Sessions store the data on the server. Only a unique Session ID (a small, random key) is passed to the browser, usually via a cookie. When the user returns, the browser sends this ID back, and PHP uses it to retrieve the full set of session data stored on the server.
This approach is highly secure because the sensitive data (like user ID, permissions, etc.) never leaves your server.
1. Starting a Session (session_start())
Every PHP script that needs to access or store session data must call session_start() first.
- This function must be called before any output is sent to the browser.
- It checks for an existing session cookie and either resumes the previous session or starts a new one by generating a unique ID.
<?php
// Starts a session or resumes the existing one
session_start();
?>
<!DOCTYPE html>
<html>
```
---
### 2. Storing and Retrieving Session Data (`$_SESSION`)
Session variables are stored in the **`$_SESSION`** superglobal array. This array is highly flexible and works just like a standard associative array.
**Example 1: Storing Login Data**
On the login validation page (`login.php`):
```php
<?php
session_start();
// Assuming validation succeeded and you fetched user data from the DB
$user_id_from_db = 105;
$user_role_from_db = 'administrator';
// Store the data in the $_SESSION array
$_SESSION['user_id'] = $user_id_from_db;
$_SESSION['role'] = $user_role_from_db;
$_SESSION['is_logged_in'] = true;
header("Location: dashboard.php");
exit;
?>
Example 2: Retrieving Data on Another Page (dashboard.php)
<?php
session_start();
// Check if the user is logged in
if ($_SESSION['is_logged_in'] !== true) {
header("Location: login.php");
exit;
}
$username = "User " . $_SESSION['user_id'];
$role = $_SESSION['role'];
echo "Welcome back, <strong>$username</strong>! Your role is $role.";
?>
3. Destroying a Session (Logout)
When a user logs out, you must clear all session variables and destroy the session to prevent unauthorized access. This is typically a three-step process:
- Start the session: Needed to access the existing session.
- Unset all session variables: Clear the data in the current session.
- Destroy the session: Delete the session data file on the server.
<?php
session_start();
// Step 1: Unset all of the session variables
$_SESSION = array();
// Step 2: Destroy the session data on the server
session_destroy();
// Optional (but good): Also delete the session cookie on the client side
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
echo "You have been logged out.";
// Redirect to the homepage or login page
// header("Location: index.php");
// exit;
?>
4. Sessions vs. Cookies (Security and Size)
| Feature | Cookies ($_COOKIE) | Sessions ($_SESSION) |
| Storage Location | Client’s web browser. | Server’s hard drive (or database). |
| Security | Less secure. Data can be viewed and tampered with by the user. | Highly secure. Only the Session ID is exposed. |
| Storage Limit | Very limited (usually 4KB per cookie). | Limited only by the server’s storage capacity. |
| Transmission | Data is sent with every HTTP request, increasing traffic. | Only the small Session ID is sent with each request. |
| Use Case | Non-sensitive data (e.g., UI preferences, non-critical tracking). | Sensitive data (e.g., user authentication, authorization levels, shopping cart details). |
