PHP $_SESSION vs $_COOKIE – Complete Guide
When developing PHP applications, you often need to store user data for later use. PHP provides two main ways to handle this:
$_SESSION
(Session variables): Store data temporarily on the server.$_COOKIE
(Cookies): Store data permanently on the user’s browser.
Let’s explore their differences, advantages, disadvantages, and real-world use cases.
1. What is $_SESSION in PHP?
PHP sessions allow you to store user data on the server and access it across multiple pages. Session data is lost when the user closes the browser or the session expires.
How to Start a PHP Session (session_start()
)
Before using $_SESSION
, you must start a session using session_start()
.
Example: Storing and Retrieving a Session Variable
<?php
session_start(); // Start the session
$_SESSION["username"] = "JohnDoe"; // Store data in session
echo "Hello, " . $_SESSION["username"]; // Retrieve session data
?>
✅ Output:Hello, JohnDoe
How to Destroy a Session (session_destroy()
)
To delete all session data, use session_destroy()
.
<?php
session_start();
session_destroy(); // Ends the session
?>
⚠️ The session is destroyed, but it still exists until the page reloads.
2. What is $_COOKIE in PHP?
PHP cookies store small amounts of user data on the browser and persist across multiple visits, even after closing the browser.
How to Set a Cookie (setcookie()
)
<?php
setcookie("user", "JohnDoe", time() + (86400 * 30), "/"); // Expires in 30 days
?>
📌 Parameters:
"user"
– Cookie name"JohnDoe"
– Cookie valuetime() + (86400 * 30)
– Cookie expiration (30 days)"/"
– Available on the entire website
How to Retrieve a Cookie ($_COOKIE
)
<?php
if(isset($_COOKIE["user"])) {
echo "Welcome back, " . $_COOKIE["user"];
} else {
echo "Cookie not found!";
}
?>
✅ Output:Welcome back, JohnDoe
(if the cookie is set)
How to Delete a Cookie
<?php
setcookie("user", "", time() - 3600, "/"); // Expired cookie
?>
⚠️ Deleting a cookie requires setting an expired timestamp.
3. Key Differences: $_SESSION vs $_COOKIE
Feature | $_SESSION | $_COOKIE |
---|---|---|
Storage | Server | Browser |
Data Expiry | Ends when browser closes or session expires | Persists until expiration date |
Security | More secure (data stored server-side) | Less secure (stored on client-side) |
Performance | Fast (server-side processing) | Slower (sent with every request) |
Use Case | Storing login data, shopping cart items, user preferences for the session | Remembering user login details, preferences, tracking data across visits |
4. When to Use $_SESSION vs $_COOKIE?
Scenario | Best Choice |
---|---|
User authentication (login sessions) | $_SESSION |
Storing temporary data (cart items) | $_SESSION |
Remembering a logged-in user (e.g., “Remember Me”) | $_COOKIE |
Tracking user preferences (e.g., dark mode) | $_COOKIE |
Storing highly sensitive data | $_SESSION (NEVER use cookies for sensitive data!) |
5. Security Considerations
A. Securing Sessions (session_regenerate_id()
)
To prevent session hijacking, regenerate session IDs regularly.
session_start();
session_regenerate_id(true);
✅ Prevents attackers from stealing active session IDs.
B. Secure Cookies (HttpOnly & Secure Flags
)
To prevent XSS attacks, set HttpOnly
and Secure
flags.
setcookie("user", "JohnDoe", time() + (86400 * 30), "/", "", true, true);
📌 Last two parameters:
✔️ true
– Ensures HTTPS only (prevents interception)
✔️ true
– Prevents JavaScript from accessing cookies (HttpOnly
)
6. Real-World Use Case: Login System ($_SESSION + $_COOKIE)
Step 1: Create a Login Form (login.html
)
<form action="login.php" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<label><input type="checkbox" name="remember"> Remember Me</label>
<button type="submit">Login</button>
</form>
Step 2: Process Login (login.php
)
<?php
session_start();
$username = "admin";
$password = "password123";
if ($_POST["username"] == $username && $_POST["password"] == $password) {
$_SESSION["user"] = $username;
if (isset($_POST["remember"])) {
setcookie("user", $username, time() + (86400 * 30), "/");
}
echo "Login successful!";
} else {
echo "Invalid login!";
}
?>
Step 3: Check Login Status (dashboard.php
)
<?php
session_start();
if (isset($_SESSION["user"]) || isset($_COOKIE["user"])) {
echo "Welcome, " . ($_SESSION["user"] ?? $_COOKIE["user"]);
} else {
echo "You must log in!";
}
?>
Step 4: Logout (logout.php
)
<?php
session_start();
session_destroy();
setcookie("user", "", time() - 3600, "/");
echo "Logged out!";
?>
✅ This system:
✔️ Uses $_SESSION
for authentication
✔️ Uses $_COOKIE
for “Remember Me” functionality
7. Conclusion: Which One Should You Use?
- Use
$_SESSION
for temporary and sensitive data (e.g., login authentication). - Use
$_COOKIE
for persistent and non-sensitive data (e.g., user preferences). - Combine both for a secure login system with “Remember Me” functionality.