The difference between session and cookies

Cookies

  • Stored: On the client-side (browser).
  • Size limit: Around 4KB.
  • Lifetime: Can be persistent (set to expire at a future time) or session-based (deleted when the browser is closed).
  • Accessibility: Can be accessed by both server and client (JavaScript).
  • Use case: Remembering user preferences, tracking, auto-login, etc.
setcookie("username", "tarikul", time() + (86400 * 30)); // Expires in 30 days

Session

  • Stored: On the server-side.
  • Size limit: Larger than cookies; limited by server memory.
  • Lifetime: Typically lasts until the browser is closed or the session times out.
  • Accessibility: Only accessible by the server.
  • Use case: Storing sensitive data like login status, cart contents, etc.
session_start();
$_SESSION["username"] = "tarikul";

Summary Table

FeatureCookiesSessions
Storage LocationClient (Browser)Server
Data Size Limit~4KBLarger (server dependent)
SecurityLess secure (exposed to client)More secure (stored on server)
LifetimeSet by developerEnds with session/browser close
AccessibilityClient & ServerServer only

Leave a Reply

Your email address will not be published. Required fields are marked *