The main difference is simple: a PHP session stores user data on the server, while a cookie stores user data in the visitor's browser. Sessions are safer and are used for login systems and shopping carts. Cookies are used for small, non-secret things like language choice, theme preference and "remember me" features. Most real websites use both together.
What Is a Cookie in PHP?
A cookie is a small text file that your website asks the browser to save on the visitor's computer or phone. The browser then sends that cookie back with every request, so your website can recognise the visitor and remember small choices.
Common examples are easy to understand. When a website remembers your dark mode setting, your language, or shows you "Welcome back" without asking anything, cookies are usually doing the work behind the scenes.
Setting a cookie in PHP takes one line:
// Save a cookie for 30 days
setcookie("username", "Lavkush", time() + (86400 * 30), "/");
// Read the cookie on the next visit
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
}
// Delete a cookie by setting a past time
setcookie("username", "", time() - 3600, "/");
Notice one rule: setcookie() must run before any HTML output on the page, because cookies are sent in the HTTP headers.
What Is a Session in PHP?
A session stores data on the server instead. When a visitor starts a session, PHP creates a unique session ID, saves the actual data safely on the server, and sends only that ID to the browser, normally inside a small cookie named PHPSESSID.
This is how login systems work. Your username, user ID and role are kept on the server, where the visitor cannot read or change them. The browser only holds a random ID that means nothing by itself.
session_start();
// Save data in the session
$_SESSION["user_id"] = 5;
$_SESSION["username"] = "Lavkush";
// Read it on any page after session_start()
echo "Hello, " . $_SESSION["username"];
// Log the user out: clear and destroy the session
session_unset();
session_destroy();
Every page that wants to use session data must call session_start() at the very top, before any output.
PHP Sessions vs Cookies: Full Comparison
| Point | Session | Cookie |
|---|---|---|
| Where data is stored | On the server | In the user's browser |
| Security | Safer — user cannot see or edit the data | Less safe — user can view and change cookie values |
| Size limit | Large, depends on server memory | Small, about 4KB per cookie |
| Lifetime | Ends when the browser closes or the session times out (often 24 minutes by default) | You choose the expiry, from minutes to months |
| Works if cookies are disabled? | Usually no, because the session ID travels in a cookie | No |
| Speed effect | Server reads a file or database record per request | Sent with every request, adds a little data |
| Best for | Login data, cart, checkout steps, private info | Preferences, language, theme, remember-me token |
When Should You Use Sessions?
Use sessions for anything private, important, or connected to identity:
- Login systems: after checking the password, store the user ID in a session. Our student registration and login system works exactly like this.
- Shopping carts: cart items belong in a session, so users cannot edit prices in the browser.
- Multi-step forms and checkouts: keep answers from step 1 safe while the user completes step 2.
- One-time messages: a "Profile saved" success message shown once after a redirect is stored briefly in the session.
When Should You Use Cookies?
Use cookies for small things that are not secret and should survive after the browser closes:
- Preferences: language, currency, dark or light theme
- Remember me: a random, hard-to-guess token that logs the user back in — never store the actual password in a cookie
- Analytics and tracking choices: for example, remembering that a visitor accepted your cookie notice
- Returning visitor comfort: pre-filling a name or city on a form
A Real Example: How a Login Uses Both
Here is what really happens when you log in to a PHP website like the admin panel of this blog. You type your email and password. PHP checks them against MySQL using PDO. If they are correct, PHP starts a session and stores your user ID on the server — that is the session doing the secure work. Then PHP sends your browser one cookie with only the session ID. On every new page, your browser shows that ID, PHP finds your data on the server, and the site knows it is you. If you also ticked "remember me", a second, longer cookie with a random token is saved, so you can return tomorrow without typing your password again. Sessions handle identity, cookies handle memory — both have a clear job.
Security Tips You Should Follow
- Never store passwords, payment details, or personal secrets in a cookie.
- Use the
httponlyflag on important cookies, so JavaScript cannot read them. - On HTTPS sites, use the
secureflag, so cookies only travel over encrypted connections. - After a successful login, call
session_regenerate_id(true)so an old session ID cannot be reused by an attacker. - Set a sensible session timeout for banking-style or admin areas, and always destroy the session on logout.
- Always escape cookie values before printing them, because users can edit their own cookies.
Frequently Asked Questions
Are sessions safer than cookies?
Yes. Session data lives on the server where users cannot see or change it. A cookie lives in the browser, so anyone can view and edit its value. Never trust important data that comes from a cookie.
Do sessions work without cookies?
Normally, no. PHP sends the session ID in a cookie. PHP can pass the ID in the URL instead, but that is less secure and not recommended for real projects.
How long does a PHP session last?
By default, PHP session data is usually kept for about 24 minutes of inactivity, and the session cookie disappears when the browser closes. You can change both settings in your PHP configuration or code.
Can a cookie store a lot of data?
No. Each cookie holds only about 4KB of text. Cookies are for small values like an ID, a token, or a setting — never for big or private data.
Sessions or cookies for a shopping cart?
Use a session for the active cart, because prices and items must stay safe on the server. Many shops also save a cookie so the cart is still there when the customer returns days later.
Conclusion
Sessions and cookies are partners, not rivals. Sessions keep private data safely on the server and power your login and cart. Cookies remember small, harmless things in the browser and make the site feel friendly on the next visit. Once you understand this difference, PHP authentication becomes much easier. Next, put it into practice with a database: read our guide on connecting PHP with a MySQL database, and follow Coding Cush for one simple coding lesson every day.
Leave a Comment