Day 11 PHP Sessions and Cookies with Examples

Day 11 PHP Sessions and Cookies with Examples
Day 11 PHP Sessions and Cookies with Examples

This comprehensive guide will help you understand the fundamental concepts of PHP Sessions and Cookies with examples, workflows, and practical applications.


What is a Cookie?

A cookie is a small file (up to 4KB) stored on the client’s device by the web server. It helps maintain state information about the user across different pages or sessions. Cookies are sent back to the server with every subsequent request.

Key Features of Cookies

  1. Domain-Specific: Cookies can only be read by the domain that issued them.
    • Example: A cookie set by www.google.com cannot be accessed by www.yahoo.com.
  2. Third-Party Cookies: Websites embedding third-party content (e.g., ads) may allow third-party cookies.
  3. Device-Specific: Cookies are stored per device and browser.
  4. User Control: Users can disable cookies, clear them, or manage their preferences.

Why and When to Use Cookies?

  • Stateless HTTP Protocol: Cookies track state across stateless HTTP requests.
  • Personalization: Store user preferences for customizing the browsing experience.
  • Session Tracking: Monitor pages visited by a user.
  • Storage Path: Cookies are stored in a folder determined by the browser, such as Temporary Internet Files for Internet Explorer.

Creating Cookies

The setcookie() function is used to create a cookie.

Syntax:

php
setcookie(name, value, expiry_time, path, domain, secure, httponly);

Parameters:

  • name (mandatory): Name of the cookie.
  • value (mandatory): Value of the cookie.
  • expiry_time (optional): Expiration time (e.g., time() + 3600 for 1 hour).
  • path (optional): Path where the cookie is available (e.g., / for the entire domain).
  • domain (optional): Domain or subdomain access restrictions.
  • secure (optional): Restrict cookies to HTTPS when true.
  • httponly (optional): Prevent access by JavaScript when true.

Example: Setting a Cookie

The following example creates a cookie that stores the username and expires in 1 minute:

php
<?php setcookie("username", "JohnDoe", time() + 60, "/"); echo "Cookie 'username' has been set for 60 seconds."; ?>

Output:

Cookie 'username' has been set for 60 seconds.

Retrieving Cookies

To retrieve cookies, use the $_COOKIE superglobal array.

php
<?php if (isset($_COOKIE['username'])) { echo "Hello, " . $_COOKIE['username']; } else { echo "Cookie 'username' is not set."; } ?>

Deleting Cookies

To delete a cookie, set its expiration time to a past time.

php
<?php setcookie("username", "", time() - 3600, "/"); echo "Cookie 'username' has been deleted."; ?>

What is a Session?

A session is a global variable stored on the server. Each session has a unique ID shared with the client via a cookie or URL. Sessions are more secure than cookies because the data is stored on the server, not the client’s device.


Key Features of Sessions

  1. Unique ID: Each session has a unique identifier for tracking.
  2. Large Data Storage: Unlike cookies, sessions can store large amounts of data.
  3. Temporary Data: Session data persists only as long as the browser is open.
  4. Fallback Mechanism: If cookies are disabled, session IDs can be appended to URLs.

Why and When to Use Sessions?

  • Sensitive Data: Store critical information (e.g., user authentication) securely.
  • Global Scope: Pass variables between pages easily.
  • Cookie Alternative: Use sessions when cookies are unavailable.
  • Larger Data Requirements: Store data exceeding cookie size limits (4KB).

Creating Sessions

Use the session_start() function to initiate a session.

php
<?php session_start(); // Start the session $_SESSION["username"] = "JohnDoe"; // Assign a session variable echo "Session 'username' is set to " . $_SESSION["username"]; ?>

Output:

Session 'username' is set to JohnDoe

Retrieving Session Data

Access session variables using the $_SESSION superglobal array.

php
<?php session_start(); // Resume the session if (isset($_SESSION["username"])) { echo "Welcome back, " . $_SESSION["username"]; } else { echo "Session 'username' is not set."; } ?>

Destroying Sessions

To remove session data:

  • Destroy Entire Session:

    php
    <?php session_start(); session_destroy(); echo "Session has been destroyed."; ?>
  • Unset a Specific Session Variable:

    php
    <?php session_start(); unset($_SESSION["username"]); echo "Session variable 'username' has been removed."; ?>

Session Workflow in Authentication

Sessions are commonly used for login systems:

  1. User logs in → Session is created.
  2. Unique session ID is stored on the server and sent to the client.
  3. Subsequent requests validate the session ID to maintain the user state.
  4. Session is destroyed upon logout or browser closure.

Cookies vs Sessions

FeatureCookiesSessions
StorageClient-sideServer-side
SecurityLess secure (can be tampered with)More secure (data stored on the server)
Size Limit4KBVirtually unlimited
LifetimePersistent until expiry or clearedEnds with browser session (or manual)
Data SharingStored in $_COOKIEStored in $_SESSION
Use CasesPersonalization, basic trackingAuthentication, sensitive information

Conclusion

Both cookies and sessions are integral to web development for maintaining user state and enhancing interactivity.

  • Use cookies for non-sensitive, lightweight, and persistent data storage.
  • Opt for sessions when security and larger data handling are priorities.

By understanding their differences and use cases, you can design robust and user-friendly web applications.

Blog categories