Difference Between Cookies and Session
Both cookies and sessions remember information about a visitor, but they keep it in different places.
| Cookie | Session | |
|---|---|---|
| Stored in | The visitor browser | The server |
| Size limit | About 4 KB | No fixed limit (depends on the server) |
| Visible to the user | Yes, the user can read and change it | No, only the session id is in the browser |
| Lifetime | Until the expiry date you set | Until the browser is closed or the session expires (about 24 minutes of inactivity by default) |
| Best for | Small, harmless data: theme, language, “remember me” token | Private data: login status, user id, shopping cart |
| PHP array | $_COOKIE | $_SESSION |
A session actually uses a cookie too, but only for the session id (called PHPSESSID). PHP uses that id to find the real data on the server. So the private data never goes to the browser.
<?php
// Cookie: stored in the browser
setcookie("theme", "dark", time() + 3600);
// Session: stored on the server
session_start();
$_SESSION["user_id"] = 25;
?>
Note:
Do not store passwords or private data in cookies, because the user can change them. Learn more in PHP Cookies and PHP Session.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| Difference Between Cookies and Session |