Link Search Menu Expand Document

Cookies and Session

HTTP is a stateless protocol. This means that the state of server-side code is not persisted from one web page to the next while a user navigates a web site.

In this module will will explore two (interrelated) techniques that allow us to transcend the statelessness of HTTP.

Table of Contents

  1. Introductions
  2. Objectives
  3. The Stateless Nature of the Web
  4. Cookies
  5. Setting a Cookie
  6. Retrieving Data from a Cookie
  7. Visit Counter Using Cookies
  8. Session
  9. Setting a Session Value
  10. Getting a Session Value
  11. Removing All Session Data

Introductions

HTTP is a stateless protocol. This means that server-side data is not persisted from one web page to the next while a user navigates a web site.

In this module will will explore two (interrelated) techniques that allow us to transcend the statelessness of HTTP: Cookies and Sessions

Objectives

Upon completion of this module, you should be able to:

  • Explain the pros and cons of the stateless nature of the web.
  • Use PHP Cookies to persist and retrieve user state.
  • Use PHP Sessions to persist and retrieve user state.
  • Write and debug PHP scripts that are “stateful”.

The Stateless Nature of the Web

URLs start with HTTP

A fundamental characteristic of the Web is the stateless interaction between browsers and web servers.

Each HTTP request a browser sends to a web server is independent of any other request. The stateless nature of HTTP allows users to browse the Web by following hypertext links and visiting pages in any order.

The stateless nature of HTTP allows users to browse the Web by following hypertext links and visiting pages in any order. HTTP also allows applications to distribute or even replicate content across multiple servers to balance the load generated by a high number of requests. These features are possible because of the stateless nature of HTTP.

This stateless nature suits applications that allow users to browse or search collections of documents. However, applications that require complex user interaction can’t be implemented as a series of unrelated, stateless web pages. An often-cited example is a shopping cart in which items are added to the cart while searching or browsing a catalog. The state of the shopping cart–the selected items–needs to be stored somewhere. When the user requests the order page, the items for that user need to be displayed.

Resources

Cookies

Nomnomnomnomnomnomnom!

Cookies are used to store user or application state in a web browser. The information is stored as a key / value pair, like in a hash.

Cookies can be set using client-side Javascript or by using HTTP headers.

We will be using the PHP setcookie function which uses HTTP headers to set cookies for us.

Resources

The setcookie function is defined as follows:

int setcookie(string key, [string value], [int expire], [string path], [string domain], [int secure])

Only the first argument is required.

To save a “name” key with a value of “wally” in a cookie:

<?php
    $ten_minutes_from_now = time() + 600;
    setcookie('name', 'wally', $ten_minutes_from_now);
?>

This cookie will expire in 10 minutes since the expire argument is set to the current time plus 600 seconds.

Arguments for the setcookie function:

  • expire: Expiration date in seconds since Epoch.
  • path: The browser will only include this cookie when requesting resources that are in the specified path. If not path is specified the cookie will be sent when requesting any resource from the specified domain.
  • domain: The browser will only include this cookie when requesting resources from this domain. If no domain is specified the browser will only include this cookie in requests set to the server which set the cookie.
  • secure: If secure is set to one then the cookie will only be sent by the browser when using a secure (SSL) connection.

When a cookie is set it is associated with a domain, a path, and an expiration. While the cookie is still fresh (i.e. it has not expired) the browser will include its information (the key/value pairs) along with any future requests made to the associated domain/path.

Once a cookie has been set, the user’s browser will make it available to future PHP scripts on the same domain.

The cookie data will be available from the $_COOKIE superglobal.

<?php
    $name = $_COOKIE['name'];
    echo $name; // Should echo "wally"
?>

Visit Counter Using Cookies

Let’s implement a simple visit counter using cookies.

<?php
    if (!isset($_COOKIE['count'])) {
        $count = 0; // No prior cookie called count, so set the counter to zero.
    } else {
        $count = $_COOKIE['count']; // retrieve previous count
        $count++;                   // Increment the count.
    }

    // Set a "count" cookie with the current visit count.
    setcookie("count", $count);
?>

The count could be displayed like so:

<!DOCTYPE html>
<html>
    <head><title>Cookies</title></head>
<body>
    <p>This page comes with cookies: Enjoy!</p>
    <p>Visit Count: <?= $count ?></p>
</body>
</html>

Session

Session support in PHP consists of a way to preserve certain data across subsequent accesses. It is built on top of cookies, but manages the setting/getting of the cookies for you.

The user information you save to a PHP session is saved server-side. All that is saved by the user’s web browser is a cookie that uniquely identifies the user.

Resources

Setting a Session Value

After the session has been started we can use the $_SESSION super-global to persist user data.

<?php
    session_start();
    $_SESSION['remember'] = 42;
?>

Getting a Session Value

If a key/value pair was previously saved to a session we can retrieve it using the $_SESSION hash.

<?php
    session_start();
    if (isset($_SESSION['remember']) {
        echo $_SESSION['remember'];
    }
?>

Removing All Session Data

There are two ways to clear previous set session data. In both cases you must first call session_start.

<?php
    session_start();

    // Method One: Manually clear our the $_SESSION hash.
    $_SESSION = [];

    // Method Two: Ask PHP to destroy all session data.
    session_destroy();

    // WARNING: Method two doesn't clear out the data until the next reload.
?>