Sessions & Cookies in PHP

From the PHP cheat sheet · Web Features · verified Jul 2026

Sessions & Cookies

Managing user sessions and cookies

php
// Sessions
session_start();
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john';

// Check session
if (isset($_SESSION['user_id'])) {
    // User is logged in
}

// Cookies
setcookie('name', 'value', time() + 3600);
$value = $_COOKIE['name'] ?? null;

// Headers
header('Content-Type: application/json');
header('Location: /dashboard');
💡 session_start() must be called before any output
⚡ Use secure, httponly, and samesite for cookie security
📌 Always exit() after header redirects
🔥 Regenerate session ID after login to prevent fixation

More PHP tasks

Back to the full PHP cheat sheet