HomePHPHow does PHP handle sessions and cookies?

How does PHP handle sessions and cookies?

PHP handles sessions and cookies to manage state in web applications, but they work differently. Let’s break it down carefully:


1. Cookies in PHP

Cookies are small pieces of data stored on the client’s browser. They persist across multiple requests until they expire (or are deleted).

Key points:

  • Stored on the client-side.
  • Can have an expiration time.
  • Sent automatically by the browser to the server with every request.

PHP functions:

  • setcookie() → To create a cookie.
  • $_COOKIE → Superglobal to read cookie values.

Example:

// Set a cookie that expires in 1 hour
setcookie("username", "Himanshu", time() + 3600, "/");

// Accessing the cookie
if(isset($_COOKIE["username"])) {
    echo "Hello, " . $_COOKIE["username"];
}

Notes:

  • Cookies must be set before any HTML output.
  • Cookies can store only small amounts of data (usually up to 4KB).

2. Sessions in PHP

Sessions are a way to store user data on the server-side, using a unique session ID to link the client to server data.

Key points:

  • Stored on the server, not the browser.
  • Each user gets a unique session ID (usually stored in a cookie called PHPSESSID).
  • More secure than cookies for sensitive data.
  • Data persists across multiple requests until the session expires or is destroyed.

PHP functions:

  • session_start() → Starts a session or resumes an existing one.
  • $_SESSION → Superglobal to store/retrieve session data.
  • session_destroy() → Ends the session.

Example:

// Start the session
session_start();

// Set session variables
$_SESSION["user_id"] = 101;
$_SESSION["username"] = "Himanshu";

// Access session variables
echo "Hello, " . $_SESSION["username"];

// Destroy session
// session_destroy();

Notes:

  • The session ID is usually sent to the browser via a cookie (PHPSESSID), but it can also be passed in the URL.
  • Sessions can store large and sensitive data securely on the server.

3. Key Differences

FeatureCookiesSessions
StorageClient-side (browser)Server-side
SecurityLess secure, visible to clientMore secure
LifetimeCan set expirationUntil browser closes or destroyed
Size limit~4KBDepends on server storage
Use casePreferences, trackingLogin, sensitive user data

💡 In practice:

  • Use cookies for non-sensitive data that needs to persist long-term.
  • Use sessions for sensitive data, like login info, that shouldn’t be stored on the client.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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