OnlineCBT Logo OnlineCBT
PHP · LESSON 13

Sessions and Cookies

By Ratan Updated: 16 Oct 2026

Maintain user authentication states using session_start(), $_SESSION, and setcookie().

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. The Need for State Management

The HTTP protocol is inherently stateless: each HTTP request is independent and has no memory of previous requests. To maintain logged-in user state, cart contents, and preferences, web applications use Cookies and Sessions.

2. PHP Cookies

A cookie is a small key-value pair stored on the client's browser. The browser transmits cookies back to the server in subsequent HTTP headers.

Setting and Reading Cookies:

 $expireTime,
    "path" => "/",
    "secure" => true,      // Transmit only over HTTPS
    "httponly" => true,    // Inaccessible to JavaScript (prevents XSS cookie theft)
    "samesite" => "Strict" // CSRF protection
]);

// Reading a cookie on subsequent requests
if (isset($_COOKIE["preferred_theme"])) {
    echo "Current theme preference: " . htmlspecialchars($_COOKIE["preferred_theme"]);
}

// Deleting a cookie: set expiration date in the past
setcookie("preferred_theme", "", time() - 3600, "/");

3. PHP Sessions

Unlike cookies which live on the client machine, session data resides securely on the server. The client only holds an opaque session identifier token (usually named PHPSESSID) inside a cookie.

Working with Sessions:

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat