PHP Sessions and Cookies – Managing User State
What Are Sessions and Cookies?
Web applications are stateless by default — each HTTP request is independent. This means the server doesn’t “remember” the user between pages.
To solve this, PHP provides:
- Sessions – Store data on the server (recommended for sensitive info)
- Cookies – Store data on the user’s browser
Together, they enable features like:
- Login/logout systems
- Shopping carts
- User preferences (dark/light theme)
- Remember-me functionality
Difference Between Sessions and Cookies
Feature | Sessions | Cookies |
---|---|---|
Stored In | Server | User’s browser |
Security | More secure | Less secure (user can modify) |
Size Limit | Larger (~20MB server-side) | Smaller (~4KB) |
Lifetime | Until browser/session ends (or manually expired) | Can persist for days or months |
Use Cases | Login data, cart contents | Remember me, preferences |
How PHP Sessions Work
- You call
session_start()
at the beginning of your script. - PHP assigns a session ID to the user.
- Data is stored server-side and linked to the ID.
- The ID is stored as a cookie in the browser.
Starting and Storing a Session
session_start()
(must be first)
<?php
session_start();
$_SESSION['username'] = "Jay";
echo "Session started!";
?>
Accessing Session Data
<?php
session_start();
echo $_SESSION['username']; // Output: Jay
?>
Destroying a Session
<?php
session_start();
session_unset(); // Clears session variables
session_destroy(); // Ends session
?>
Creating and Using Cookies
Set a Cookie
setcookie("username", "Jay", time() + (86400 * 7)); // 7 days
time() + seconds
sets expiration- This must be called before any HTML output
Read a Cookie
echo $_COOKIE["username"];
Delete a Cookie
setcookie("username", "", time() - 3600);
Example: Simple Login System Using Sessions
📄 login.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = $_POST['username'];
$pass = $_POST['password'];
if ($user === "admin" && $pass === "1234") {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $user;
header("Location: dashboard.php");
} else {
echo "Invalid credentials!";
}
}
?>
<form method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
📄 dashboard.php
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
header("Location: login.php");
exit;
}
echo "Welcome, " . $_SESSION['username'] . "!<br>";
echo "<a href='logout.php'>Logout</a>";
?>
📄 logout.php
<?php
session_start();
session_destroy();
header("Location: login.php");
?>
Best Practices
- Always call
session_start()
at the top of every session-using file - Use cookies for non-sensitive data (like theme, preferences)
- Always sanitize data before storing in a session or cookie
- Set cookie expiration and secure flags where possible:
setcookie("example", "value", time()+3600, "/", "", true, true);
- Destroy sessions properly on logout (
session_unset()
+session_destroy()
)
Common Mistakes
- Sending output before calling
session_start()
orsetcookie()
- Not checking
isset()
before accessing session or cookie variables - Storing sensitive data in cookies (always use sessions instead)
- Not destroying sessions after logout (security risk)
Notes:
- Sessions store user data on the server and are more secure
- Cookies store small pieces of data on the client (browser)
- Sessions are ideal for login/authentication
- Always destroy sessions on logout and avoid storing raw passwords in any storage
Practice Tasks
Task 1: Build a Welcome Page
If $_SESSION['username']
is set, show a personalized message. Otherwise, redirect to login.php
.
Task 2: Remember Theme Using Cookies
Create a dropdown that lets the user choose “Dark” or “Light” mode. Store the selection in a cookie and remember it for 7 days.
Task 3: Auto-Login via Cookie
After login, offer a “Remember Me” checkbox. If selected, set a cookie remember_user
. On next visit, auto-login based on that cookie.
💡 Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.