Thuta Learning
AdvancedProgrammingbeginner

Sessions & Cookies

Relax. We'll talk through this in plain words — no textbook voice.

Sessions and cookies are used to store user state. A session is stored server-side, and only the session id lives in the user's browser. A cookie stores data inside the browser itself. They're commonly used for things like login state, cart count, and preferences.

php
<?php
session_start();

$_SESSION["user_name"] = "Aung Aung";

setcookie("theme", "dark", time() + (86400 * 30), "/");

echo "Session user: " . $_SESSION["user_name"];
?>
You should see
Session user: Aung Aung

Easy traps

  • If you call setcookie() after HTML output has already been sent, you may get a headers already sent error.
Sessions & Cookies | Thuta Learning