Skip to main content
PHP for Beginners
CHAPTER 09 Beginner

PHP Sessions and Cookies

Updated: May 12, 2026
20 min read

# CHAPTER 9

PHP Sessions and Cookies

1. Introduction

By default, the internet has amnesia. The HTTP protocol is "stateless"—meaning every time you click a link or refresh a page, the server completely forgets who you are. If this were true in practice, you would have to type your password on every single page of a website. To solve this, backend developers use Sessions and Cookies to give the server a "memory," allowing users to stay logged in and keep items in their shopping carts.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the stateless nature of HTTP.
  • Start and manage PHP Sessions using $SESSION.
  • Differentiate between Sessions (server-side) and Cookies (client-side).
  • Implement basic user tracking across multiple pages.

3. Beginner-Friendly Explanation

Imagine going to an amusement park. The ticket booth (the Server) sells you an unlimited ride pass. But the ride operators (the Web Pages) have no memory of you. If you just walk up to a ride, they will ask you to pay again. To solve this, the ticket booth gives you a Wristband with a unique ID number. Now, when you walk up to a ride, you show your wristband. The operator checks the number, confirms you paid, and lets you on. In web development, a Session is the record the server keeps in its database. A Cookie is the wristband the server gives to your browser to prove who you are.

4. What is a PHP Session?

A Session is a way to store information (in variables) to be used across multiple pages. The data is stored securely on the Web Server, not on the user's computer.

Starting a Session: To use session variables, you MUST call sessionstart() at the very top of your PHP file, before any HTML is sent to the browser.

Page 1: Setting the Session (login.php)

php
12345678910
<?php
// Must be the very first line
session_start();

// Simulating a successful login
$_SESSION["username"] = "Alice";
$_SESSION["role"] = "Admin";

echo "Session variables are set. Go to the dashboard.";
?>

Page 2: Reading the Session (dashboard.php)

php
12345678910
<?php
session_start(); // Must start the session here too to access the memory!

if (isset($_SESSION["username"])) {
    echo "Welcome back, " . $_SESSION["username"];
    echo "Your role is: " . $_SESSION["role"];
} else {
    echo "You are not logged in!";
}
?>

5. Destroying a Session (Logging Out)

When a user clicks "Log Out", you must manually destroy the session data on the server so nobody else can access their account.
php
1234567891011
<?php
session_start();

// Remove all session variables
session_unset();

// Destroy the session entirely
session_destroy();

echo "You have been securely logged out.";
?>
A Cookie is a small text file that the server sends to the user's Web Browser. The browser saves it on the user's hard drive. Unlike Sessions (which disappear when the user closes their browser), Cookies can be set to last for months. This is how websites implement the "Remember Me" checkbox.

Setting a Cookie:

php
12345678
<?php
$cookie_name = "preferred_theme";
$cookie_value = "dark_mode";
$expiration = time() + (86400 * 30); // 86400 = 1 day. Expires in 30 days.

// Send the cookie to the browser
setcookie($cookie_name, $cookie_value, $expiration, "/");
?>

Reading a Cookie:

php
12345
<?php
if(isset($_COOKIE["preferred_theme"])) {
    echo "Your theme is set to: " . $_COOKIE["preferred_theme"];
}
?>

7. Sessions vs. Cookies

FeaturePHP SessionsHTTP Cookies
Storage LocationStored securely on the Server.Stored insecurely on the User's Browser.
SecurityHigh. Users cannot see or edit the data.Low. Users can view, edit, and delete them.
LifespanEnds when the browser is closed.Can last for years, specified by the developer.
Best Used ForLogged-in status, sensitive cart totals.Theme preferences, non-sensitive "Remember Me" tokens.

8. Backend Workflow: The Complete Login Flow

  1. 1. User submits login form.
  1. 2. PHP checks MySQL. Password matches!
  1. 3. PHP creates a Session: $SESSION['userid'] = 5;
  1. 4. PHP redirects user to dashboard.php.
  1. 5. dashboard.php reads $SESSION['userid'] and displays their private data.

9. Best Practices

  • Never Store Passwords in Sessions/Cookies: Never put sensitive data like passwords or credit card numbers in a session or a cookie. Only store non-sensitive identifiers, like the user's ID number or a randomized token.

10. Common Mistakes

  • "Headers Already Sent" Error: sessionstart() and setcookie() must modify the HTTP Headers. If you accidentally leave a blank space, echo a word, or write <html> *before* calling sessionstart(), PHP will throw a fatal error. Logic goes at the top, HTML goes at the bottom.

11. Exercises

  1. 1. Explain why an e-commerce site uses a Session to store the items in a shopping cart rather than relying entirely on a stateless HTTP request.

12. Coding Challenges

  • Challenge: Create a PHP script that uses a Session variable to count how many times a user has refreshed the page. (Hint: if(isset($SESSION['views'])) { $SESSION['views']++; })

13. MCQs with Answers

Question 1

Because HTTP is a "stateless" protocol, backend developers use PHP Sessions to give the server a "memory." Where is PHP Session data physically stored?

Question 2

Which built-in PHP function must be called at the very top of your script before you can read or write to the $SESSION array?

14. Interview Questions

  • Q: Contrast PHP Sessions and HTTP Cookies. When would you choose to use a Session, and when would you use a Cookie?
  • Q: Explain the "Headers already sent" error. Why does sessionstart() trigger this if it is placed in the middle of a file?

15. FAQs

Q: Do Sessions use Cookies to work? A: Yes! By default, when PHP starts a Session, it generates a random gibberish ID (like PHPSESSID=123xyz) and sends it to the browser as a temporary Cookie. The browser sends that Cookie back on every click, allowing the server to match the browser to the correct Session file on the server.

16. Summary

In Chapter 9, we cured the internet's amnesia. By utilizing $
SESSION, we can securely store user data on the server across multiple page loads, enabling robust features like authentication and shopping carts. By utilizing setcookie(), we can store long-term, non-sensitive preferences directly on the user's browser.

17. Next Chapter Recommendation

We know how to keep a user logged in, but how do we securely verify their password in the first place? Proceed to Chapter 10: User Authentication and Login Systems.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·