Imagine logging into a website, and every time you refresh, you get logged out—frustrating, right? 😩 That’s because web pages don’t remember users by default. This is where PHP sessions and cookies save the day!
In this guide, we’ll break down how to use sessions and cookies, explore security best practices, and build a mini login system. 🎯
🎯 What Are PHP Sessions and Cookies?
Feature | Session | Cookie |
---|---|---|
Stored | On the server | On the user’s browser |
Lifetime | Until the user closes the browser (or set timeout) | Until expiration date (can last months) |
Security | More secure (data stays server-side) | Less secure (data can be modified by users) |
Best for | User authentication, carts, temporary data | Remembering logins, preferences, tracking |
🔥 When to use what?
- Use Sessions for sensitive data like login credentials.
- Use Cookies for persistent data like user preferences.
1️⃣ PHP Sessions: Storing Temporary User Data
A session stores user data on the server and assigns a unique session_id
to each user.
Starting a Session
<?php
session_start(); // Always start a session
$_SESSION["username"] = "Zero Dev";
echo "Session stored!";
?>
🔥 What happens?
session_start()
initializes the session.$_SESSION["username"]
stores"Zero Dev"
for this user.
2️⃣ Retrieving Session Data
Sessions persist across pages until the user closes the browser or the session expires.
<?php
session_start();
if (isset($_SESSION["username"])) {
echo "Welcome, " . $_SESSION["username"] . "!";
} else {
echo "Session not found!";
}
?>
🔥 Why?
- If the session exists, it greets the user.
- If not, it tells them session data isn’t available.
3️⃣ Destroying a Session (Logging Out)
<?php
session_start();
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session
echo "Logged out!";
?>
🔥 Why? This clears user data, logging them out.
4️⃣ PHP Cookies: Storing Persistent User Data
A cookie is a small piece of data stored on the user’s device.
Creating a Cookie
<?php
setcookie("username", "Zero Dev", time() + (86400 * 7)); // Expires in 7 days
?>
🔥 What happens?
- The cookie stores
"Zero Dev"
and expires in 7 days.
5️⃣ Retrieving Cookie Data
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"] . "!";
} else {
echo "Cookie not found!";
}
?>
🔥 Why?
- If the cookie exists, it greets the user.
- If not, it doesn’t remember them.
6️⃣ Deleting a Cookie
<?php
setcookie("username", "", time() - 3600); // Set to a past time to delete
?>
🔥 Why? The expiration is set to the past, deleting it.
🎯 Mini Project: Login System with Sessions & Cookies
Let’s build a simple login system that: ✅ Uses sessions to keep users logged in
✅ Uses cookies to "remember" users
login.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
if ($username == "zerodev" && $password == "secret123") {
$_SESSION["username"] = $username;
if (isset($_POST["remember"])) {
setcookie("username", $username, time() + (86400 * 7)); // 7 days
}
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>
Remember Me: <input type="checkbox" name="remember"><br>
<input type="submit" value="Login">
</form>
dashboard.php
<?php
session_start();
if (!isset($_SESSION["username"]) && isset($_COOKIE["username"])) {
$_SESSION["username"] = $_COOKIE["username"]; // Auto-login with cookie
}
if (!isset($_SESSION["username"])) {
echo "Access denied! <a href='login.php'>Login here</a>";
exit;
}
echo "Welcome, " . $_SESSION["username"] . "! <a href='logout.php'>Logout</a>";
?>
logout.php
<?php
session_start();
session_unset();
session_destroy();
setcookie("username", "", time() - 3600); // Delete cookie
header("Location: login.php");
?>
✅ What’s Happening?
login.php
checks credentials and stores a session.- If "Remember Me" is checked, it also stores a cookie.
dashboard.php
checks for a session; if none, it uses the cookie to auto-login.logout.php
clears both session and cookie data.
🔥 Boom! You now have a real-world login system! 🚀
🚀 Final Thoughts
Now you know how to store user data in PHP!
✅ Use Sessions for temporary data like logins
✅ Use Cookies for persistent data like "Remember Me"
✅ Secure your app by encrypting cookies and managing session timeouts
👉 Next: File Uploading in PHP
Happy coding! 🎉🚀
Sessions and Cookies are two different things and make sure you understand them well.