PHP Cookies & Sessions

Remember users between requests.

✍️ 2 exercises in this lesson

Cookies

A cookie is a small value stored in the user's browser: setcookie("theme", "dark", time() + 86400 * 30);. Read it with $_COOKIE["theme"].

Sessions

A session stores data on the server, linked to the user by a session id cookie. It is the standard way to keep users logged in.

  1. session_start(); at the very top of every page that uses sessions.
  2. Save: $_SESSION["user"] = "Ali";
  3. Read: $_SESSION["user"]
  4. Log out: session_destroy();
Call session_regenerate_id(true) after login to prevent session-fixation attacks.

Key Takeaways: PHP Cookies & Sessions

Mastering PHP Cookies & Sessions helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Cookies & Sessions Code Example

PHP
<?php
session_start();
setcookie("theme", "dark", time() + 60 * 60 * 24 * 30);

$_SESSION["views"] = ($_SESSION["views"] ?? 0) + 1;

echo "You have viewed this page {$_SESSION['views']} times.<br>";
echo "Theme cookie: " . ($_COOKIE["theme"] ?? "not set yet");
Output
You have viewed this page 3 times.
Theme cookie: dark
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Cookies & Sessions Practice Exercises

Check what you learned in “PHP Cookies & Sessions”.

/ 2 solved
Fill in the blank

Start the session before using $_SESSION.

();
✓ Correct! Not quite. Try again.
Multiple choice

Where is session data stored?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services