Cookies & Sessions in Web Development Complete Guide with Easy Examples
Cookies vs Sessions are fundamental concepts in web development. They allow websites to remember users, maintain login states, store preferences, and provide personalized experiences.
HTTP is inherently stateless, meaning a web server does not automatically remember one request from another. Cookies and sessions solve this problem by providing mechanisms for maintaining information across multiple requests.
In this guide, we will learn what cookies and sessions are, how they work, their differences, security considerations, and a practical real-life example.

Table of Contents
What Are Cookies?
A cookie is a small piece of data that a website asks the user’s web browser to store.
When the browser visits the website again, it can send the cookie back to the server. This allows the website to recognize information associated with that browser.
For example, a website might store:
- Language preference
- Theme preference
- Shopping cart identifier
- Login-related information
- Tracking identifiers
- Website preferences
Simple Example
Suppose you visit an online store and select:
Language: English
The website can store this preference in a cookie.
When you return later, the browser sends the cookie, allowing the website to display the English version automatically.
How Cookies Work
The basic process looks like this:
User visits website
↓
Server sends HTTP response
↓
Server includes Set-Cookie header
↓
Browser stores cookie
↓
User makes another request
↓
Browser sends cookie with request
↓
Server reads cookie
For example, a server may send:
Set-Cookie: theme=dark; Max-Age=86400
The browser stores the cookie:
theme = dark
On a later request, the browser may send:
Cookie: theme=dark
The server can then use that information.
Creating a Cookie in PHP
In PHP, a cookie can be created using setcookie().
<?php
setcookie(
“username”,
“Ali”,
time() + 86400,
“/”,
“”,
true,
true
);
echo “Cookie created.”;
Here:
- username = cookie name
- Ali = cookie value
- time() + 86400 = expiration time
- / = available throughout the website
- true = Secure flag
- true = HttpOnly flag
The Secure and HttpOnly options should be used appropriately in production.
Reading a Cookie in PHP
Cookies are available through the $_COOKIE superglobal.
<?php
if (isset($_COOKIE[“username”])) {
echo “Welcome, ” . htmlspecialchars($_COOKIE[“username”]);
} else {
echo “Cookie not found.”;
}
Deleting a Cookie
To delete a cookie, set its expiration time to the past.
<?php
setcookie(
“username”,
“”,
time() – 3600,
“/”
);
The browser will remove the cookie.
What Is a Session?
A session is a server-side mechanism used to maintain information about a user across multiple HTTP requests.
Unlike a normal cookie value, session data is generally stored on the server.
The browser usually receives a session identifier, commonly through a cookie, which allows the server to associate subsequent requests with the correct session data.
For example:
Browser
│
│ Session ID
↓
Server
│
└── Session Data
├── user_id
├── username
├── role
└── login status
How Sessions Work
Consider a user logging into a website.
Step 1: User Logs In
The user submits:
Username: Ali
Password: ********
Step 2: Server Verifies Credentials
The server checks the username and password against the database.
Step 3: Server Creates a Session
The server creates session data such as:
user_id = 25
username = Ali
role = student
Step 4: Browser Receives Session Identifier
The browser receives a session identifier.
Step 5: User Visits Another Page
The browser sends the session identifier with the request.
Step 6: Server Finds the Session
The server uses the identifier to retrieve:
user_id = 25
username = Ali
role = student
The website therefore knows that the request belongs to Ali.
Creating a Session in PHP
First, start the session:
<?php
session_start();
$_SESSION[“user_id”] = 25;
$_SESSION[“username”] = “Ali”;
$_SESSION[“role”] = “student”;
echo “Session created.”;
The important function is:
session_start();
It must be called before accessing or modifying session data.
Reading Session Data
<?php
session_start();
if (isset($_SESSION[“username”])) {
echo “Welcome, ” . htmlspecialchars($_SESSION[“username”]);
} else {
echo “User is not logged in.”;
}
Destroying a Session
When the user logs out, the session should be properly terminated.
<?php
session_start();
$_SESSION = [];
if (ini_get(“session.use_cookies”)) {
$params = session_get_cookie_params();
setcookie(
session_name(),
“”,
time() – 42000,
$params[“path”],
$params[“domain”],
$params[“secure”],
$params[“httponly”]
);
}
session_destroy();
echo “Logged out successfully.”;
This removes the server-side session data and expires the session cookie.
Cookies vs Sessions
The main difference is where the information is maintained.
| Feature | Cookies | Sessions |
| Storage | Browser/client | Server |
| Data sent with requests | Cookie data | Usually session ID |
| Security | More exposed to client | Generally safer for sensitive state |
| Size | Limited | Depends on server-side storage |
| Expiration | Can be persistent | Usually temporary, depending on configuration |
| Common use | Preferences, identifiers | Authentication, user state |
| Client can directly modify value | Yes | Session data is normally server-side |
| Requires server storage | No | Yes |
Example: Online Shopping Cart
A shopping website provides an excellent example of cookies and sessions working together.
Imagine you visit:
example-shop.com
You select:
Laptop
Wireless Mouse
Keyboard
The website needs to remember your shopping activity.
Using a Cookie
The website could store a cart identifier:
cart_id = A8F92K
The browser sends this identifier whenever it communicates with the website.
The server can use that identifier to locate the corresponding cart.
The actual cart contents can be stored server-side or in a database.
Example: Login System
Now consider an educational website.
You log in with:
Email: student@example.com
Password: ********
After successful authentication, the server creates a session:
user_id = 105
name = Ahmed
role = student
The browser receives a session identifier.
When you open:
/dashboard
the browser sends the session identifier.
The server checks the session and determines:
User ID: 105
Role: Student
Authenticated: Yes
The dashboard can therefore display:
Welcome, Ahmed!
You do not have to enter your username and password on every page.
Analogy: Hotel Room Key
A simple way to understand sessions is to think about a hotel.
When you check into a hotel, the receptionist creates a record for you:
Guest:
Ahmed
Room:
205
You receive a room key.
The key does not contain your complete guest information. Instead, it identifies which room you are authorized to access.
Similarly:
Browser → Session ID → Server → Session Data
The session ID acts somewhat like the hotel room key, while the actual session information remains on the server.
Cookies and Sessions Working Together
Cookies and sessions are not necessarily competing technologies. They often work together.
A typical authentication flow looks like this:
LOGIN
│
▼
Server verifies
credentials
│
▼
Session is created
│
▼
Session ID generated
│
▼
Session ID stored in cookie
│
▼
Browser stores cookie
│
▼
User requests dashboard
│
▼
Browser sends session ID
│
▼
Server finds session
│
▼
User is authenticated
This is one of the most common uses of cookies and sessions in web applications.
Cookies vs Sessions: Which Should You Use?
The answer depends on what information you need to maintain.
Use Cookies for:
- Non-sensitive preferences
- Language selection
- Theme selection
- Remembering certain client-side preferences
- Identifiers that are appropriate to store client-side
Use Sessions for:
- Authentication state
- User IDs
- Roles and permissions
- Temporary server-side application state
- Sensitive state that should not be directly controlled by the browser
Do not store passwords in cookies or sessions.
Cookie Security
Cookies can introduce security risks if they are configured incorrectly.
Important cookie attributes include:
1. Secure
The Secure attribute tells the browser to send the cookie only over HTTPS.
Secure
This helps prevent exposure over unencrypted HTTP connections.
2. HttpOnly
The HttpOnly attribute prevents JavaScript from directly accessing the cookie through document.cookie.
HttpOnly
This can reduce the impact of certain cross-site scripting (XSS) attacks involving cookies.
3. SameSite
SameSite controls when browsers send cookies in cross-site requests.
Common values include:
Strict
Lax
None
For many applications, Lax or Strict is appropriate depending on the authentication and cross-site requirements.
Session Security
Sessions are especially important for authentication, so they must be protected carefully.
Regenerate the Session ID After Login
A common security practice is to regenerate the session identifier after successful authentication:
<?php
session_start();
session_regenerate_id(true);
$_SESSION[“user_id”] = 105;
$_SESSION[“role”] = “student”;
This helps defend against session fixation attacks.
Never Trust Session-Related Client Input
Do not assume that a value supplied by the browser is trustworthy.
For example, never allow a user to become an administrator simply by changing:
role=user
to:
role=admin
Authorization should be determined by trusted server-side data, preferably from the database and authenticated session context.
Session Hijacking
A session hijacking attack occurs when an attacker obtains a valid user’s session identifier and attempts to use it to impersonate that user.
For example:
Victim
↓
Logs into website
↓
Session ID created
↓
Attacker obtains session ID
↓
Attacker sends session ID
↓
Server recognizes valid session
The attacker may then gain access to the victim’s account.
Using HTTPS, secure cookie attributes, session regeneration, appropriate session expiration, and other authentication controls can significantly reduce this risk.
Example: Simple PHP Login Session
A simplified example might look like this:
<?php
session_start();
$username = $_POST[“username”] ?? “”;
$password = $_POST[“password”] ?? “”;
// Example only.
// In a real application, verify credentials against
// a database using password_verify().
if ($username === “admin” && $password === “secret”) {
session_regenerate_id(true);
$_SESSION[“user_id”] = 1;
$_SESSION[“username”] = “admin”;
$_SESSION[“role”] = “administrator”;
echo “Login successful.”;
} else {
echo “Invalid username or password.”;
}
Important: This is only a learning example. Production authentication should use a database, password_hash(), password_verify(), CSRF protection, HTTPS, secure session configuration, validation, rate limiting, and proper authorization.
Common Mistakes
Developers often make mistakes when implementing cookies and sessions.
Mistake 1: Storing Passwords
Never store passwords in cookies or sessions.
Mistake 2: Storing Sensitive Information in Plain Cookies
Cookies are controlled by the client and should not be treated as trusted storage.
Mistake 3: Forgetting session_start()
Without starting the session, PHP cannot properly access the current session.
Mistake 4: Not Regenerating Session IDs
Regenerate the session identifier during important authentication transitions, especially after login.
Mistake 5: Using HTTP Instead of HTTPS
Authentication cookies should be protected by HTTPS.
Mistake 6: Trusting Client-Side Roles
Never rely on a browser-controlled value such as:
role=admin
for authorization.
Cookies and Sessions in Modern Web Applications
Modern applications may use additional technologies such as:
- JSON Web Tokens (JWT)
- OAuth 2.0
- OpenID Connect
- Redis-backed sessions
- Database-backed sessions
- Server-side session stores
- Secure authentication cookies
However, the fundamental concept remains the same:
The application needs a reliable way to associate multiple HTTP requests with the correct user or application state.
Conclusion
Cookies and Sessions are essential components of web development.
Cookies allow websites to store small amounts of information in the user’s browser, while sessions allow applications to maintain user-related state on the server.
The easiest way to remember the difference is:
Cookie
↓
Stored in the browser
Session
↓
Stored on the server
Session Cookie
↓
Usually contains the identifier
that connects the browser to
the server-side session
A real-world login system demonstrates how they work together: the server creates a session after successful authentication, the browser stores the session identifier in a cookie, and subsequent requests use that identifier to retrieve the user’s server-side session.
Understanding cookies and sessions is therefore essential for anyone learning PHP, WordPress, Laravel, Core PHP, authentication, web development, or backend programming.


