← Back to PHP Course | Chapter 12: Sessions & Cookies | Lesson 2 of 5

PHP Session Management

Session Security Checks

Session hijacking happens when an attacker steals a valid session ID and impersonates the user; regenerating the session ID with session_regenerate_id() right after login invalidates any ID an attacker may already have captured.

Example: Session Security Checks

php
<?php
session_start();
session_regenerate_id(true);
echo "Session ID regenerated after login";
?>

Setting Session Timeout Limits

A simple timeout pattern stores a last-activity timestamp in $_SESSION and checks it on every page load, forcing a logout if too much time has passed -- protecting accounts left open on shared or public computers.

Example: Setting Session Timeout Limits

php
<?php
session_start();
$timeout = 1800;
$_SESSION['last_activity'] = time() - 2000;
if (time() - $_SESSION['last_activity'] > $timeout) {
    echo "Session expired -- logging out";
} else {
    $_SESSION['last_activity'] = time();
}
?>

Custom Session Configuration

Before calling session_start(), you can configure cookie lifetime, path, and security flags with session_set_cookie_params(), giving you control over how long a session cookie survives and where it's valid.

Example: Custom Session Configuration

php
<?php
session_set_cookie_params(3600, '/', '', true, true);
session_start();
echo "Session cookie configured before starting";
?>

Session Status and States

session_status() tells you whether sessions are disabled, inactive, or already active, which is useful for guarding against calling session_start() twice or checking session state before performing sensitive actions.

Example: Session Status and States

php
<?php
echo session_status() === PHP_SESSION_NONE ? "No session yet\n" : "Session active\n";
session_start();
echo session_status() === PHP_SESSION_ACTIVE ? "Now active" : "Still inactive";
?>

Session Name and ID

session_name() and session_id() let you inspect or override the identifiers PHP uses under the hood, which matters when running multiple independent apps on the same domain that shouldn't share session data.

Example: Session Name and ID

php
<?php
session_start();
echo session_name() . ": " . session_id();
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.