HTTP is stateless — each request forgets the last. Sessions give you per-visitor memory on the server.
Starting a session
session_start() must run before any output (no HTML, no echo, not
even a blank line before <?php).
PHP
<?php
session_start();
$_SESSION['user_id'] = 42;
$_SESSION['name'] = 'Sita';Reading it back on another page
PHP
<?php
session_start();
if (isset($_SESSION['user_id'])) {
echo "Welcome, " . htmlspecialchars($_SESSION['name']);
} else {
header('Location: /login.php');
exit;
}How it works
PHP stores the data on the server and sends the browser a PHPSESSID
cookie holding only the session id. The visitor never sees the data —
but they do control the id, which is why the security notes below matter.
Logging out
PHP
<?php
session_start();
$_SESSION = []; // clear the data
session_destroy(); // destroy the server-side session
// also remove the cookie
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$p['path'], $p['domain'], $p['secure'], $p['httponly']);
}Session fixation
Regenerate the id whenever privileges change — above all, right after a successful login. Otherwise an attacker who planted a known session id keeps access:
PHP
<?php
// after verifying the password
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];Hardening
PHP
<?php
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => true, // HTTPS only
'httponly' => true, // JavaScript cannot read it
'samesite' => 'Lax', // basic CSRF protection
]);
session_start();Never put trust decisions in a cookie the visitor controls — store the
user id in $_SESSION and look up their role from the database.