Lesson 12 — Web Development

Sessions and Cookies

HTTP is stateless by nature — sessions and cookies are how PHP remembers a visitor between separate page requests, powering logins, shopping carts, and preferences.

Sessions

A session stores data on the server, identified by a unique session ID stored in a cookie on the visitor's browser. Calling session_start() at the top of every script that needs session access is required before reading or writing to $_SESSION.

PHP — Using sessions
<?php
session_start();

$_SESSION['username'] = 'Karabo';

// On a later page load:
if (isset($_SESSION['username'])) {
    echo "Welcome back, " . $_SESSION['username'];
}
?>

Cookies

Cookies store small amounts of data directly in the visitor's browser rather than on the server, useful for longer-lived, less sensitive preferences like a "remember me" setting.

PHP — Setting a cookie
setcookie("theme", "dark", time() + (86400 * 30)); // expires in 30 days

Common Mistakes

  • Forgetting session_start() at the very top of a script (before any HTML output), which prevents session data from being read or written.
  • Storing sensitive data like passwords in a cookie, which lives on the client and can be inspected or tampered with.
  • Confusing sessions (server-side, more secure) with cookies (client-side, less secure) when choosing where to store something.
  • Not calling session_destroy() (and clearing $_SESSION) when logging a user out, leaving old session data accessible.

Professional Tip

Store only a session identifier in the cookie sent to the browser, and keep the actual sensitive data — like login state or cart contents — in server-side session storage. This keeps meaningful data out of reach of the client.

Your Turn

Build a simple login simulation: a form that sets $_SESSION['loggedIn'] = true on submit, a page that only displays content if that session variable is set, and a logout script that destroys the session.

Mini Quiz

What must be called at the very top of a PHP script before using $_SESSION?