The web is inherently stateless – each HTTP request is independent, meaning the server doesn’t remember who you are between page loads. But modern applications need to maintain – whether that’s a logged-in session, items in a shopping cart, or personalized preferences.
This is where sessions & cookies in PHP come in. PHP provides built-in mechanisms to handle both, making it easy to maintain stateful experiences in otherwise stateless environments.
What are Cookies?
A cookie is a small piece of data stored on the client’s browser. The server sets cookies, and the browser sends them back with every request to the same domain.
Example: Setting & Reading Cookies in PHP
<?php // Setting a cookie (expires in 1 hour) setcookie("user", "Karthick", time() + 3600, "/"); // Reading a cookie if(isset($_COOKIE["user"])) { echo "Welcome back, " . $_COOKIE["user"]; } else { echo "Hello, Guest!"; }
👉 Cookies are best for lightweight, client-side preferences (e.g., language settings, theme).
What are Sessions?
A session is server-side storage linked to a unique session ID (usually stored in a cookie). Unlike cookies, session data is not exposed to the client.
Example: Creating & Using a Session in PHP
<?php session_start(); // Always start session before output // Set session variables $_SESSION["username"] = "Karthick"; $_SESSION["role"] = "Admin"; // Access session variables echo "User: " . $_SESSION["username"];
👉 Sessions are used for sensitive data like authentication, shopping carts, or temporary storage.
How Sessions Work in PHP
- A client sends a request to the server.
- PHP generates a Session ID and stores it on the server.
- The Session ID is sent to the browser as a cookie (PHPSESSID).
- On each subsequent request, the browser sends back the Session ID, and the server retrieves the session data.
Cookies vs Sessions
Feature | Cookies | Sessions |
---|---|---|
Storage | Client-side (browser) | Server-side |
Security | Less secure (stored on client) | More secure (server managed) |
Size Limit | ~4KB | Depends on server storage |
Lifetime | Can persist (until expiry) | Usually ends when browser closes |
Use Cases | Preferences, language, theme | Authentication, shopping carts |
Example: Login Using Sessions
<?php session_start(); // Mock login check if ($_POST['username'] == 'admin' && $_POST['password'] == '1234') { $_SESSION['loggedin'] = true; echo "Login successful!"; } else { echo "Invalid credentials!"; }
Then on a protected page:
<?php session_start(); if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) { die("Access Denied!"); } echo "Welcome to the dashboard!";
👉 This is the basis of authentication systems in PHP and frameworks like Laravel.
Security Best Practices
- Always use HTTPS so cookies/sessions aren’t intercepted.
- Use HttpOnly & Secure flags for cookies.
setcookie("auth", "xyz", time()+3600, "/", "", true, true);
- Regenerate Session IDs after login to prevent session fixation attacks.
session_regenerate_id(true);
- Never store sensitive data directly in cookies.
Laravel Connection
In Laravel, session and cookie handling is abstracted and simplified.
- Sessions can be stored in file, database, Redis, or array drivers.
Example in Laravel:
// Store in session session(['user' => 'Karthick']); // Retrieve $user = session('user');
👉 Middleware like web
ensures session state is maintained automatically in Laravel.
Common Mistakes Beginners Make
- Forgetting
session_start()
at the top of PHP scripts. - Mixing cookies and sessions without understanding differences.
- Storing sensitive data (like passwords) in cookies.
- Not expiring or clearing sessions on logout.
Sample Interview Questions & Answers
Q: What’s the difference between a session and a cookie?
A: Sessions are stored on the server, while cookies are stored on the client’s browser. Sessions are more secure for sensitive data.
Q: How does PHP know which session belongs to which user?
A: By using the Session ID, usually stored in a cookie named PHPSESSID
.
Q: Can you store sessions without cookies?
A: Yes, by passing the Session ID in the URL, though it’s less secure.
Q: What happens if a user disables cookies?
A: PHP can still use sessions, but the Session ID must be passed via URL (less common and less secure).
Q: How do you destroy a session in PHP?
A:
session_start(); session_unset(); session_destroy();
Q: How does Laravel manage sessions differently from raw PHP?
A: Laravel uses a unified session manager with multiple drivers (file, DB, Redis), automatically handling session start and regeneration.
Closing Note
Sessions & Cookies in PHP are the foundation of state management. For beginners, mastering these concepts is crucial before moving into frameworks like Laravel, where authentication, middleware, and guards depend on them.
Continue Your PHP Journey
Master these essential PHP topics:
- PHP basics for web developers – Build a solid foundation
- Common PHP myths busted – Separate fact from fiction
- Understanding PHP OOP concepts – Level up your code structure
- PHP error handling and debugging – Debug like a pro
0 Comments