Handling user authentication, shopping carts, and preferences in PHP? Youβll need sessions and cookies!
π― In this guide, youβll learn:
β
The difference between sessions and cookies
β
How to use PHP sessions securely
β
How to store user data in cookies
β
How to implement a simple login system with sessions
β
Best security practices for session handling
By the end, youβll have a fully functional session-based authentication system! π
1οΈβ£ What Are Sessions and Cookies?
π‘ Sessions and cookies both store user data, but they work differently.
Feature | Sessions | Cookies |
---|---|---|
Stored In | Server | Userβs browser |
Data Type | Can store complex data (arrays, objects) | Stores only strings |
Security | More secure (data is not exposed to users) | Less secure (stored in userβs browser) |
Lifetime | Ends when the user closes the browser (unless configured) | Can persist for days/weeks |
Best For | User authentication, shopping carts | Remembering user preferences |
π₯ Which one should you use?
β
Use sessions for authentication & sensitive data.
β
Use cookies for storing user preferences (e.g., dark mode, language settings).
2οΈβ£ Using PHP Sessions
π‘ Sessions store user data on the server and assign a unique session_id
to each user.
1οΈβ£ Starting a Session
<?php
session_start(); // Always start the session at the top
$_SESSION["username"] = "Zero Dev"; // Storing data in session
echo "Hello, " . $_SESSION["username"];
?>
π₯ Whatβs happening?
β
session_start()
creates or resumes a session.
β
$_SESSION
stores data server-side.
2οΈβ£ Accessing Session Data
<?php
session_start();
echo "Welcome back, " . $_SESSION["username"]; // Output: Welcome back, Zero Dev
?>
3οΈβ£ Destroying a Session (Logout)
<?php
session_start();
session_destroy(); // Removes all session data
header("Location: login.php"); // Redirect user
?>
π₯ Why destroy sessions?
β
Prevents unauthorized access after logout.
3οΈβ£ Using PHP Cookies
π‘ Cookies store small pieces of data in the user's browser.
1οΈβ£ Setting a Cookie
<?php
setcookie("username", "Zero Dev", time() + 3600, "/"); // Expires in 1 hour
?>
π₯ Whatβs happening?
β
setcookie(name, value, expiration, path)
creates a cookie.
β
Lasts for 1 hour (time() + 3600
).
2οΈβ£ Accessing a Cookie
<?php
if (isset($_COOKIE["username"])) {
echo "Hello, " . $_COOKIE["username"];
}
?>
π₯ Why use cookies?
β
Stores lightweight user preferences (e.g., theme, language).
3οΈβ£ Deleting a Cookie
<?php
setcookie("username", "", time() - 3600, "/"); // Set expiration in the past
?>
π₯ Why delete cookies?
β
Resets user preferences.
4οΈβ£ Mini Project: Login System with Sessions
π Letβs build a simple login system using sessions.
1οΈβ£ Create login.php
(User Login)
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
if ($username == "admin" && $password == "12345") { // Simple authentication
$_SESSION["user"] = $username;
header("Location: dashboard.php");
} else {
echo "Invalid login credentials!";
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="Enter Username" required>
<input type="password" name="password" placeholder="Enter Password" required>
<button type="submit">Login</button>
</form>
π₯ What happens?
β
Stores the username in a session after login.
β
Redirects the user to dashboard.php.
2οΈβ£ Create dashboard.php
(Protected Page)
<?php
session_start();
if (!isset($_SESSION["user"])) {
header("Location: login.php"); // Redirect if not logged in
exit();
}
echo "Welcome, " . $_SESSION["user"];
?>
<a href="logout.php">Logout</a>
π₯ Why check for $_SESSION["user"]
?
β
Prevents unauthorized users from accessing the dashboard.
3οΈβ£ Create logout.php
<?php
session_start();
session_destroy(); // Remove session data
header("Location: login.php"); // Redirect to login page
?>
π₯ Now users can log out securely! π
5οΈβ£ Best Security Practices for Sessions & Cookies
β
Use HTTPS: Encrypts session & cookie data.
β
Regenerate Session ID on login:
session_regenerate_id(true);
β
Set HttpOnly
& Secure
flags for cookies:
setcookie("user", "Zero Dev", time() + 3600, "/", "", true, true);
β Use session timeout:
if (!isset($_SESSION["LAST_ACTIVITY"]) || time() - $_SESSION["LAST_ACTIVITY"] > 1800) {
session_unset(); session_destroy();
}
$_SESSION["LAST_ACTIVITY"] = time();
π₯ Why?
β Prevents session hijacking.
β Improves security.
π Final Thoughts
Now you know how to handle sessions and cookies like a pro!
β
Use sessions for authentication
β
Use cookies for lightweight data
β
Secure your sessions with best practices
π Next: File Upload Handling in PHP
Happy coding! ππ