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
Page 2: Reading the Session (dashboard.php)
php
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
6. What is a Cookie?
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
Reading a Cookie:
php
7. Sessions vs. Cookies
| Feature | PHP Sessions | HTTP Cookies |
|---|---|---|
| Storage Location | Stored securely on the Server. | Stored insecurely on the User's Browser. |
| Security | High. Users cannot see or edit the data. | Low. Users can view, edit, and delete them. |
| Lifespan | Ends when the browser is closed. | Can last for years, specified by the developer. |
| Best Used For | Logged-in status, sensitive cart totals. | Theme preferences, non-sensitive "Remember Me" tokens. |
8. Backend Workflow: The Complete Login Flow
- 1. User submits login form.
- 2. PHP checks MySQL. Password matches!
-
3.
PHP creates a Session:
$SESSION['userid'] = 5;
-
4.
PHP redirects user to
dashboard.php.
-
5.
dashboard.phpreads$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()andsetcookie()must modify the HTTP Headers. If you accidentally leave a blank space, echo a word, or write<html>*before* callingsessionstart(), PHP will throw a fatal error. Logic goes at the top, HTML goes at the bottom.
11. Exercises
- 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 (likePHPSESSID=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.