Skip to main content

Course Progress

Loading...

Working with Sessions and Cookies in PHP

Duration: 60 minutes
Module 2: Sessions and Cookies

Learning Objectives

  • Master PHP programming concepts
  • Write clean, maintainable code
  • Apply best practices
  • Build dynamic applications

Introduction to State Management in Web Applications

Welcome to our exploration of sessions and cookies in PHP! This fundamental topic allows us to create dynamic, personalized web experiences by solving one of the web's most fundamental challenges: maintaining state in a stateless protocol.

The Amnesia Analogy

Imagine HTTP (the protocol that powers the web) as a person with severe amnesia. Each time you interact with them, they completely forget who you are and all previous conversations. Without any mechanism to maintain "memory," every webpage would treat you like a stranger with each click, regardless of whether you had just logged in or added items to a shopping cart.

Cookies and sessions are like the memory aids we provide to this amnesiac:

  • Cookies are like sticky notes we attach directly to the visitor. They carry small bits of information that remain with the user as they browse.
  • Sessions are like a personal file we keep on our side, with a unique identifier tag we give to the visitor. When they return with that tag, we can retrieve all their information from our files.
Diagram
Sequence Diagram (Diagram converted to static representation) sequenceDiagram participant User participant Brows...

Without cookies or sessions, each interaction with a website requires starting from scratch—re-entering credentials, losing shopping carts, and personalizations that make modern web applications useful. Let's explore how PHP helps us overcome this limitation.

Understanding Cookies

What Are Cookies?

Cookies are small text files stored on the user's browser. They contain small pieces of data specific to a particular website and user, allowing websites to "remember" information about visitors between page views.

The Concert Stamp Analogy

Think of cookies like hand stamps at a concert:

  • They're placed directly on the visitor
  • They allow re-entry without repeating the ticket process
  • They have a specific duration (one night)
  • They can only be read by the venue that issued them
  • They contain minimal information (just "admitted")

Similarly, cookies mark your browser with small bits of data that websites can check when you return, letting them recognize you without requiring re-authentication or preference setting with each click.

Diagram
Sequence Diagram (Diagram converted to static representation) sequenceDiagram participant User participant Brows...

Creating Cookies in PHP

PHP provides the setcookie() function to create cookies. This function must be called before any output is sent to the browser, as it sets HTTP headers.

Basic Cookie Creation

###CODE_BLOCK_1###

setcookie() Parameters Explained

Parameter Description Example
name The name of the cookie "user_name"
value The value to store (must be a string) "John"
expires When the cookie expires (as Unix timestamp) time() + 3600 (1 hour)
path The path on the server where the cookie is available "/" (entire domain)
domain The domain where the cookie is available "example.com"
secure Cookie should only be transmitted over HTTPS true
httponly Cookie accessible only through HTTP protocol (not JavaScript) true

Reading Cookies in PHP

Reading cookies is straightforward; PHP automatically populates the $_COOKIE superglobal array with all cookies sent by the browser.

Reading Cookies

###CODE_BLOCK_3###

Modifying and Deleting Cookies

To modify a cookie, simply set it again with the same name. To delete a cookie, set it with an expiration time in the past.

Modifying and Deleting Cookies

###CODE_BLOCK_4###

Important Cookie Considerations

  • Size Limitations: Cookies are limited to about 4KB in size.
  • Security: Never store sensitive information (passwords, credit card numbers) in cookies.
  • Headers: setcookie() must be called before any output is sent to the browser.
  • Cookie Law: Many jurisdictions require explicit user consent for non-essential cookies.
  • Accessibility: Don't rely exclusively on cookies; some users disable them.

Real-World Cookie Applications

  • User Preferences: Saving display settings, language choices, theme preferences
  • Remembering Form Data: Preventing re-entry of information
  • "Remember Me" Functionality: Keeping users logged in between sessions
  • Basic Analytics: Tracking returning visitors
  • Shopping Carts: For non-logged-in users (though sessions are often preferred)

Cookie-Based Theme Switcher Example

###CODE_BLOCK_6###

Understanding Sessions

What Are Sessions?

Sessions are a server-side mechanism for maintaining state. Unlike cookies, which store data on the client's browser, session data is stored on the server, with only a session identifier stored as a cookie on the client.

The Coat Check Analogy

Think of sessions like a coat check at a fancy restaurant:

  • You arrive (start browsing) and hand over your belongings (data)
  • The coat check gives you a numbered ticket (session ID cookie)
  • While you dine (browse), the restaurant securely holds your belongings
  • When you need something, you present your ticket and get access to your stuff
  • When you leave (close browser), they eventually dispose of unclaimed items (session expires)

The key distinction from regular cookies is that with sessions, your actual belongings (data) stay at the restaurant (server) rather than you carrying them around, making them more secure and allowing for larger amounts of data.

Diagram
Sequence Diagram (Diagram converted to static representation) sequenceDiagram participant User participant Brows...

Starting and Configuring Sessions in PHP

PHP makes session management straightforward with built-in functions. Like cookies, session operations must occur before any output is sent to the browser.

Starting a Session

###CODE_BLOCK_7###

Working with Session Data

After starting a session, you can read and write session data using the $_SESSION superglobal array.

Storing and Retrieving Session Data

###CODE_BLOCK_9###

Modifying and Removing Session Data

You can modify session values just like any array, and remove items using unset().

Modifying and Removing Session Data

###CODE_BLOCK_11###

Important Session Considerations

  • Session Hijacking: Protect the session ID from theft (use HTTPS and httponly cookies)
  • Session Fixation: Regenerate session IDs upon privilege changes (like login)
  • Server Storage: Sessions consume server resources; use carefully with high-traffic sites
  • Session Lifetime: Consider both cookie lifetime and server garbage collection settings
  • Session Files: Default storage is in temporary files; production should use a more robust solution

Session Security Best Practices

Secure Session Implementation

###CODE_BLOCK_12###

Alternative Session Storage

By default, PHP stores session data in files on the server. For production applications, especially those with multiple servers, you may want to use alternative storage mechanisms.

Custom Session Handlers

###CODE_BLOCK_13###

Production Alternatives for Session Storage

  • Redis: In-memory data store, excellent for session data
  • Memcached: Distributed memory caching system
  • Database: MySQL, PostgreSQL, etc.
  • MongoDB: NoSQL alternative for flexible session data

For WordPress-specific applications, note that WordPress has its own session handling that internally uses cookies rather than PHP's native sessions.

Practical Applications: Sessions vs. Cookies

When to Use What?

Feature Cookies Sessions
Storage Location Client (Browser) Server (with only ID stored on client)
Size Limit ~4KB Limited only by server resources
Lifespan Can persist for years Typically until browser closes or timeout
Security Less secure (client-side) More secure (server-side)
Accessibility Accessible to JavaScript Not directly accessible to client-side code
Server Load Minimal (client handles storage) Higher (server manages storage)
Scale Considerations Works well at any scale Requires special handling for distributed systems

Best Use Cases

Use Cookies For:

  • Remembering language preferences
  • Theme selections
  • "Remember me" login functionality
  • Tracking anonymous users
  • Storing non-sensitive user preferences
  • Performance optimization (avoiding database queries)

Use Sessions For:

  • User authentication state
  • Shopping carts
  • Temporary workflow data
  • Storing sensitive user information
  • Form data between multi-step forms
  • Flash messages

Real-World Application Examples

Shopping Cart Implementation

###CODE_BLOCK_14###

User Authentication with Sessions

###CODE_BLOCK_15###

Remember Me Functionality (Cookies + Sessions)

###CODE_BLOCK_16###

Flash Messages with Sessions

###CODE_BLOCK_17###

Sessions and Cookies in WordPress

While we've covered general PHP session and cookie handling, WordPress has its own approach to state management. Understanding how WordPress handles sessions and cookies is essential for developing WordPress plugins and themes.

WordPress and Sessions

WordPress does not use PHP sessions by default. This is primarily for scalability and performance reasons, as PHP sessions can cause issues in distributed environments. Instead, WordPress relies heavily on cookies for maintaining state.

Why WordPress Avoids PHP Sessions

  • Performance: Sessions create files on the server for each user, which can lead to filesystem bottlenecks
  • Scalability: Session files cause issues in load-balanced environments with multiple servers
  • Compatibility: Some hosting environments restrict or modify session handling
  • Cleanup: Orphaned session files can accumulate if not properly managed

WordPress Authentication Cookies

WordPress uses a sophisticated cookie-based authentication system:

  • wordpress_[hash]: Authentication cookie for logged-in users
  • wordpress_logged_in_[hash]: Contains username and login expiration
  • wordpress_sec_[hash]: Secure version of the auth cookie (HTTPS)
  • wp-settings-{user_id}: User-specific interface settings

WordPress Authentication

###CODE_BLOCK_18###

Adding Session Support to WordPress

If you need traditional session functionality in WordPress, you have several options:

Custom Session Handler for WordPress

###CODE_BLOCK_19###

Important Considerations for WordPress Sessions

  • Using sessions in WordPress can cause compatibility issues with some caching plugins
  • Session-based plugins may not work properly in load-balanced environments without special configuration
  • Consider using WordPress transients or user meta for persistent data when possible
  • If you must use sessions, consider a database-backed session handler for better compatibility

Alternative State Management in WordPress

Instead of sessions, WordPress provides several built-in mechanisms for state management:

WordPress Transients

###CODE_BLOCK_20###

User Meta for Persistent User Data

###CODE_BLOCK_21###

Custom Cookies in WordPress

###CODE_BLOCK_22###

Security Best Practices Summary

Diagram
(Session/Cookie Security

Essential Security Checklist

  • Use HTTPS exclusively - Secure transmission for all cookies and session data
  • Set the Secure flag - Ensures cookies are sent only over HTTPS connections
  • Set the HttpOnly flag - Prevents JavaScript access to cookies
  • Use SameSite attribute - Prevents CSRF attacks (Strict or Lax)
  • Set appropriate expiration times - Balance security and user experience
  • Regenerate session IDs - Especially after authentication or privilege changes
  • Never store sensitive data in cookies - Use server-side storage instead
  • Implement proper logout procedures - Clear all session data and cookies
  • Use CSRF tokens - For all form submissions that modify data
  • Consider alternative storage mechanisms - Database or Redis instead of files
  • Validate session data - Check consistency and origin on each request
  • Implement session timeouts - Both absolute and idle timeouts

Secure Session Configuration

###CODE_BLOCK_25###

Conclusion and Next Steps

Sessions and cookies are fundamental to creating dynamic, personalized web applications with PHP. They allow you to maintain state in the stateless HTTP protocol, remember user preferences, implement authentication, and create seamless user experiences.

Key Takeaways

  • Cookies are client-side - Small text files stored in the user's browser
  • Sessions are server-side - Data stored on the server with only an ID stored on the client
  • Security is critical - Always implement best practices for cookie and session security
  • Different use cases - Choose cookies for non-sensitive, long-term data and sessions for sensitive, temporary data
  • WordPress has its own approach - Understand WordPress's cookie-based authentication system

Next Topic: Creating Reusable PHP Components

In our next session, we'll build on our knowledge of sessions and cookies to create reusable PHP components that can be shared across multiple pages or projects. We'll explore techniques for building modular, maintainable code that simplifies development and improves code quality.

Additional Resources

Practice Assignment

Shopping Cart Implementation

Create a simple shopping cart system using PHP sessions that allows users to:

  1. Add products to their cart
  2. Update product quantities
  3. Remove products from their cart
  4. View their cart with subtotal and total calculations
  5. Clear their entire cart

Requirements:

  • Implement secure session handling following best practices
  • Create a product listing page with "Add to Cart" functionality
  • Implement a cart page that displays all cart items and totals
  • Include quantity adjustments and product removal options
  • Add a "Continue Shopping" button that returns to product listings
  • Implement a "Checkout" button (just simulate the process)

Bonus Challenge:

  • Add a "Remember Cart" feature using cookies that persists for 7 days
  • Implement cart merging when a user logs in (combine their stored cart with their session cart)