PHP Basics · Chapter 15 · Sessions & Cookies

PHP Sessions & Cookies
Complete Guide in Hindi

PHP Sessions और Cookies की पूरी जानकारी — User login state maintain करना, shopping cart, Remember Me feature, Flash messages, Session security। Real examples के साथ।

🔐 Sessions 🍪 Cookies 🛒 Cart 💬 Flash Messages 🛡️ Security
$_SESSIONServer पर store होता है
$_COOKIEBrowser पर store होता है
24minDefault session lifetime
4KBMax cookie size

📋 इस Article में क्या-क्या है

  1. Sessions vs Cookies — फर्क
  2. Session — Start, Set, Get
  3. Session Destroy करना
  4. Session Security
  5. Cookies — setcookie()
  6. Cookie Read & Delete
  7. Real World — Login System
  8. Shopping Cart
  9. Flash Messages
  10. Remember Me Feature
1
Sessions vs Cookies — फर्क क्या है?

दोनों user data store करने के तरीके हैं — लेकिन Session server पर save होती है और Cookie browser पर। Login, cart, preferences — सब के लिए अलग-अलग use होते हैं।

FeatureSessionCookie
Store होता हैServer पर (PHP files/DB)User के browser पर
Security✅ More secure❌ User edit कर सकता है
Size limitServer disk तक4KB max
LifetimeBrowser close = end (default)Years तक रह सकती है
AccessPHP onlyPHP + JavaScript
Best forLogin, cart, sensitive dataPreferences, Remember Me
Superglobal$_SESSION$_COOKIE
Sessions = Sensitive data (login, cart)। Cookies = Persistent preferences (theme, language, Remember Me)।

2
Session — Start, Set, Get करना
sess
ion

session_start()

हर page पर सबसे पहले session_start() call करो। Output से पहले — headers already sent error आएगी। एक बार start करने के बाद $_SESSION array use करो।

Output से पहले! हर page पर $_SESSION array
SESSION — BASIC USAGE
<?php
// ⚠️ Output से बिल्कुल पहले — whitespace भी नहीं
session_start();

// SET — session variables
$_SESSION["user_id"] = 42;
$_SESSION["user_naam"] = "Rahul Kumar";
$_SESSION["role"] = "admin";
$_SESSION["logged_in"] = true;

// GET — session variables read
echo $_SESSION["user_naam"]; // Rahul Kumar
echo $_SESSION["user_id"]; // 42

// isset — check करो पहले
if (isset($_SESSION["user_id"])) {
  echo "Logged in as: " . $_SESSION["user_naam"];
} else {
  echo "Please login";
}

// Session ID और Name
echo session_id(); // Unique session identifier
echo session_name(); // Default: PHPSESSID

// Session में Array भी store कर सकते हो
$_SESSION["cart"] = [
  ["id" => 1, "name" => "PHP Book", "price" => 450]
];
?>
⚠️ Headers Already Sent Error: session_start() से पहले कोई output नहीं होना चाहिए — echo, HTML, whitespace भी नहीं। PHP file की पहली line <?php होनी चाहिए — BOM या blank lines नहीं।

3
Session Destroy — Logout करना
SESSION DESTROY — COMPLETE LOGOUT
<?php
session_start();

// Method 1 — Single variable हटाओ
unset($_SESSION["user_id"]);

// Method 2 — सब variables हटाओ (session रहे)
$_SESSION = [];

// Method 3 — Complete Logout (recommended)
function logout(): void {
  session_start();
  $_SESSION = []; // Step 1: data clear

  // Step 2: Session cookie delete
  if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(
      session_name(), "",
      time() - 42000, // Past = delete
      $params["path"], $params["domain"],
      $params["secure"], $params["httponly"]
    );
  }
  session_destroy(); // Step 3: destroy
}

logout();
header("Location: login.php");
exit;
?>

4
Session Security — Attacks से बचाव
SESSION SECURITY — BEST PRACTICES
<?php
// 1. Session Fixation रोको — login के बाद नया ID
function secureLogin(int $userId, string $naam): void {
  session_start();
  session_regenerate_id(true); // ✅ New session ID!
  $_SESSION["user_id"] = $userId;
  $_SESSION["user_naam"] = $naam;
  $_SESSION["logged_in"] = true;
  $_SESSION["login_time"] = time();
  $_SESSION["user_agent"] = md5($_SERVER["HTTP_USER_AGENT"]);
}

// 2. Session Hijacking check — हर request पर
function isSessionValid(): bool {
  if (!isset($_SESSION["logged_in"])) return false;

  // User Agent मिलता है?
  if ($_SESSION["user_agent"] !== md5($_SERVER["HTTP_USER_AGENT"])) {
    logout(); return false;
  }
  // 30 min timeout
  if (time() - $_SESSION["login_time"] > 1800) {
    logout(); return false;
  }
  $_SESSION["login_time"] = time(); // Activity update
  return true;
}

// 3. Secure php.ini settings
ini_set("session.cookie_httponly", 1); // JS access block
ini_set("session.cookie_secure", 1); // HTTPS only
ini_set("session.cookie_samesite", "Strict"); // CSRF protection
ini_set("session.gc_maxlifetime", 1800); // 30 min
?>
Attackक्या होता हैProtect कैसे करें
Session FixationAttacker अपना session ID force करता हैLogin पर session_regenerate_id(true)
Session HijackingSession ID चुराकर login करनाUser-Agent check, HTTPS, HttpOnly
CSRFदूसरी site से requestSameSite=Strict cookie
XSS cookie theftJS से cookie चुरानाHttpOnly cookie flag

5
Cookies — setcookie() से Create करना
🍪
cook

setcookie()

User के browser में cookie save करता है। Output से पहले call करना ज़रूरी। Browser अगली request में वापस भेजता है — $_COOKIE से read करो।

Output से पहले! Browser में store Persistent storage
setcookie() — ALL OPTIONS
<?php
// Simple cookie — browser close पर expire
setcookie("theme", "dark");

// 30 days cookie
setcookie("lang", "hi", time() + (30 * 24 * 3600));

// Fully secure cookie (old syntax)
setcookie(
  "user_pref", "dark_mode",
  time() + (365 * 24 * 3600), // 1 year
  "/", "", // path, domain
  true, // HTTPS only
  true // HttpOnly
);

// PHP 7.3+ — Array options (recommended)
setcookie("token", "abc123", [
  "expires" => time() + 86400,
  "path" => "/",
  "secure" => true,
  "httponly" => true,
  "samesite" => "Strict"
]);
?>

6
Cookie Read & Delete करना
COOKIE — READ & DELETE
<?php
// READ — $_COOKIE superglobal
if (isset($_COOKIE["theme"])) {
  echo $_COOKIE["theme"]; // dark
}

// Safe read — null coalescing
$theme = $_COOKIE["theme"] ?? "light";
$lang = $_COOKIE["lang"] ?? "en";

// DELETE — past time set करो
setcookie("theme", "", time() - 3600);
unset($_COOKIE["theme"]); // Current request के लिए भी
?>
⚠️ $_COOKIE Trust मत करो: User-controlled है — edit हो सकती है। Sensitive data (user_id, role) cookies में plain text store मत करो। Session use करो या signed tokens।

7
Real World — Complete Login System
LOGIN — login.php
<?php
session_start();

// Already logged in?
if (isset($_SESSION["user_id"])) {
  header("Location: dashboard.php"); exit;
}

$error = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $email = trim($_POST["email"] ?? "");
  $password = $_POST["password"] ?? "";

  $user = loginUser(getDB(), $email, $password);

  if ($user) {
    session_regenerate_id(true);
    $_SESSION["user_id"] = $user["id"];
    $_SESSION["user_naam"] = $user["naam"];
    $_SESSION["role"] = $user["role"];
    $_SESSION["login_time"] = time();
    header("Location: dashboard.php"); exit;
  } else {
    $error = "❌ Invalid email or password";
  }
}
?>
AUTH CHECK — हर protected page पर
<?php
// auth.php — include करो हर protected page पर
session_start();

function requireLogin(string $redirect = "login.php"): void {
  if (!isset($_SESSION["user_id"])) {
    header("Location: $redirect"); exit;
  }
}

function requireRole(string $role): void {
  requireLogin();
  if ($_SESSION["role"] !== $role) {
    http_response_code(403);
    die("403 Forbidden — Access Denied");
  }
}

// dashboard.php — login check
require_once "auth.php";
requireLogin();
echo "Welcome, {$_SESSION['user_naam']}!";

// admin.php — role check
requireRole("admin");
?>

8
Shopping Cart — Session से
SHOPPING CART — Session Based
<?php
session_start();
if (!isset($_SESSION["cart"])) $_SESSION["cart"] = [];

function addToCart(int $id, string $name, float $price, int $qty = 1): void {
  if (isset($_SESSION["cart"][$id])) {
    $_SESSION["cart"][$id]["qty"] += $qty; // qty बढ़ाओ
  } else {
    $_SESSION["cart"][$id] = compact("id", "name", "price", "qty");
  }
}

function removeFromCart(int $id): void {
  unset($_SESSION["cart"][$id]);
}

function cartTotal(): float {
  return array_sum(array_map(
    fn($i) => $i["price"] * $i["qty"], $_SESSION["cart"]
  ));
}

function cartCount(): int {
  return array_sum(array_column($_SESSION["cart"], "qty"));
}

addToCart(1, "PHP Book", 450);
addToCart(2, "Laravel", 799, 2);
echo "Items: " . cartCount(); // 3
echo "Total: ₹" . number_format(cartTotal(), 2); // ₹2,048.00
?>

9
Flash Messages — One-Time Messages
FLASH MESSAGES — PRG Pattern
<?php
function setFlash(string $type, string $message): void {
  $_SESSION["flash"] = ["type" => $type, "message" => $message];
}

function getFlash(): ?array {
  if (!isset($_SESSION["flash"])) return null;
  $flash = $_SESSION["flash"];
  unset($_SESSION["flash"]); // ✅ एक बार के बाद delete
  return $flash;
}

// profile_save.php — save → flash → redirect
setFlash("success", "✅ Profile updated successfully!");
header("Location: profile.php"); exit;

// profile.php — message दिखाओ
$flash = getFlash();
if ($flash) {
  echo "<div class='alert-{$flash['type']}'>{$flash['message']}</div>";
}
?>
PRG Pattern: Post → Redirect → Get। Form submit के बाद redirect करो — double submit रुकता है। Flash message redirect के बाद page पर दिखता है।

10
Remember Me — Persistent Login
REMEMBER ME — Secure Token System
<?php
// DB Table: remember_tokens (user_id, token_hash, expires_at)

function setRememberMe(PDO $pdo, int $userId): void {
  $token = bin2hex(random_bytes(32)); // Secure random
  $tokenHash = hash("sha256", $token); // DB में hash
  $expires = date("Y-m-d H:i:s", strtotime("+30 days"));

  $pdo->prepare("INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?,?,?)")
     ->execute([$userId, $tokenHash, $expires]);

  // Cookie में user_id:plain_token
  setcookie("remember_token", $userId . ":" . $token, [
    "expires" => strtotime("+30 days"),
    "path" => "/",
    "secure" => true,
    "httponly" => true,
    "samesite" => "Strict"
  ]);
}

function checkRememberMe(PDO $pdo): bool {
  if (!isset($_COOKIE["remember_token"])) return false;

  [$userId, $token] = explode(":", $_COOKIE["remember_token"], 2);
  $tokenHash = hash("sha256", $token);

  $stmt = $pdo->prepare("SELECT u.* FROM users u JOIN remember_tokens rt ON rt.user_id = u.id WHERE rt.user_id=? AND rt.token_hash=? AND rt.expires_at > NOW()");
  $stmt->execute([$userId, $tokenHash]);
  $user = $stmt->fetch();

  if ($user) {
    session_regenerate_id(true);
    $_SESSION["user_id"] = $user["id"];
    $_SESSION["user_naam"] = $user["naam"];
    return true;
  }
  return false;
}
?>
Pattern: random_bytes() → SHA256 hash → DB में hash, Cookie में plain → Check: hash compare → session set
💡 Security: Cookie में plain token, DB में hash — DB breach होने पर भी token useless। हमेशा random_bytes() use करो — rand() नहीं।

Quick Reference
FunctionकामNote
session_start()Session शुरू करोOutput से पहले, हर page
session_regenerate_id(true)New session ID generateLogin के बाद ज़रूर
session_destroy()Session deleteLogout पर
$_SESSION["key"]Session data set/getServer-side
unset($_SESSION["key"])Single var deletePartial clear
setcookie($name,$val,$exp)Cookie createOutput से पहले
$_COOKIE["key"]Cookie readBrowser-side, trust मत
setcookie($name,"",time()-1)Cookie deletePast time = delete

निष्कर्ष

Sessions और Cookies PHP web development का core हैं। Login, cart, preferences — सब इन्हीं से होता है। Security पर ध्यान दो।

session_start() — हर page पर सबसे पहले। Output से पहले।

session_regenerate_id(true) — Login के बाद ज़रूर। Session Fixation रोकता है।

Logout — $_SESSION = [] → session_destroy() → PHPSESSID cookie delete।

Cookies — HttpOnly + Secure + SameSite=Strict। $_COOKIE trust मत करो।

Flash Messages — setFlash() → redirect → getFlash() + unset()।

Remember Me — random_bytes() → hash → DB। Cookie में plain token।

🚀 अगला Chapter: Chapter 16: PHP OOP — Class, Object, Constructor, Inheritance।