Introduction
In PHP, sessions and cookies are used to store user data so it can be accessed across multiple pages.
They play a crucial role in building real-world applications such as login systems, shopping carts, and personalized user experiences.
Sessions store data on the server, while cookies store data in the user’s browser. Understanding the difference between sessions and cookies is essential for building secure and dynamic web applications.
What You’ll Learn
- What PHP sessions and cookies are
- Difference between sessions and cookies
- How to create, read, and delete sessions
- How to create, read, and delete cookies
- Real-life login example
- Common mistakes and security tips
Difference Between Sessions and Cookies
| Feature | Session | Cookie |
|---|---|---|
| Stored in | Server | User’s browser |
| Lifetime | Until browser closes (default) | Set by developer |
| Security | More secure | Less secure |
| Data size | Larger | Small |
| Use cases | Login state, cart | Preferences, remember me |
PHP Sessions
A session is a way to store user data on the server. PHP assigns each visitor a unique session ID. This ID is usually stored in the browser as a small cookie, and PHP uses it to retrieve the correct session data on every request.
Starting a Session
Before using sessions, you must start one.
session_start();
⚠️ This must be the first line of your PHP file (before any HTML).
Setting Session Variables
session_start();
$_SESSION['username'] = "Divyesh";
$_SESSION['role'] = "Admin";
Accessing Session Variables
session_start();
echo $_SESSION['username'];
Removing Session Variables
Unset a specific session variable
unset($_SESSION['username']);
Destroy all session data
session_destroy();
Real-Life Example: Login Session
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['username'] = $_POST['username'];
echo "Login successful";
}
if (isset($_SESSION['username'])) {
echo "Welcome " . $_SESSION['username'];
} else {
echo "Please login";
}
PHP Cookies
A cookie is a small piece of data stored in the user’s browser. Cookies can be used to remember preferences or small pieces of non-sensitive information between visits.
Common uses of cookies:
- Remembering theme preference
- Saving language choice
- “Remember me” functionality
- Tracking basic user settings
Creating a Cookie
<?php
setcookie("user", "Divyesh", time() + 3600); // Expires in 1 hour
?>
This cookie will expire in 1 hour.
Accessing a Cookie
<?php
if (isset($_COOKIE['user'])) {
echo "Hello, " . $_COOKIE['user'];
}
?>
Deleting a Cookie
setcookie("user", "", time() - 3600);
When to Use Cookies
- Remember login (Remember Me)
- Store user preferences
- Track visits
When to Use Sessions vs Cookies
✔ Use Sessions when:
- Managing login systems
- Data is sensitive
- Storing user-specific data securely
✔ Use Cookies when:
- Storing user preferences
- Remembering settings
- Data is non-sensitive
Security Tips (Important)
- Never store passwords in cookies
- Regenerate session IDs for login systems
- Use sessions for sensitive data
- Always validate session data
- Destroy sessions on logout
Essential PHP Session & Cookie Functions (Quick Reference)
This section lists the most commonly used functions when working with sessions and cookies in PHP. Understanding these will help you manage user data, login systems, and preferences more effectively.
🔹 Session Functions
1️⃣ session_start()
Starts a new session or resumes an existing one.
session_start();
📌 Must be called before any HTML output
📌 Required to use $_SESSION
2️⃣ $_SESSION
Superglobal array used to store session data.
$_SESSION['username'] = 'DivPHP';
📌 Data is stored on the server
📌 Available across pages
3️⃣ session_unset()
Removes all session variables.
session_unset();
📌 Clears data but session still exists
4️⃣ session_destroy()
Destroys the session completely.
session_destroy();
📌 Logs the user out
📌 Session ID becomes invalid
5️⃣ session_id()
Gets or sets the current session ID.
echo session_id();
📌 Useful for debugging and advanced use cases
🔹 Cookie Functions
1️⃣ setcookie()
Creates a cookie in the user’s browser.
setcookie("theme", "dark", time() + 3600, "/");
📌 Stored on client browser
📌 Expires after 1 hour
📌 Must be set before any output
2️⃣ $_COOKIE
Reads cookie values.
echo $_COOKIE['theme'];
📌 Only available on next request
📌 User can delete cookies manually
3️⃣ unset($_COOKIE['name'])
Removes cookie variable from PHP runtime.
unset($_COOKIE['theme']);
📌 Does NOT delete browser cookie
4️⃣ Deleting a Cookie Properly
setcookie("theme", "", time() - 3600, "/");
📌 This actually deletes the cookie from browser
Common Mistakes to Avoid
- Forgetting
session_start() - Outputting HTML before starting session
- Storing sensitive data in cookies
- Trying to read cookies immediately after setting them
- Not destroying sessions on logout
Practical Tasks
Task 1. Create a session variable
Create a session that stores your name and display it on another page.
Task 2. Build a simple login system
Create a form where a user enters a username and store it in a session after submission.
Task 3. Destroy session on logout
Add a logout button that destroys the session and redirects the user.
Task 4. Create and read a cookie
Store a user’s preferred theme (light/dark) using cookies and display it on the page.
Task 5. Delete a cookie
Create a button to delete the cookie and check if it is removed.
Task 6. Session vs Cookie experiment
Store the same data using both session and cookie and observe the difference.
Task 7. Security practice
Try modifying cookie values manually in the browser and see how it affects your application.
Conclusion
In this tutorial, you learned how PHP sessions and cookies work and how they are used to store user data across multiple pages.
Sessions store data on the server and are more secure, making them ideal for login systems and sensitive information. Cookies, on the other hand, are stored in the browser and are useful for remembering user preferences.
You also learned how to create, access, and delete sessions and cookies, along with important security best practices.
Understanding sessions and cookies is essential for building secure and dynamic PHP applications.
In the next tutorial, we’ll learn about PHP Include & Require
