HTTP Cookies
&
PHP Sessions

OBJECTIVES

In this unit, the student will learn:
  • how to work with HTTP cookies in PHP:
    • setting a cookie
    • retrieving and testing a cookie
    • deleting a cookie
  • how to work with HTTP cookies in JavaScript
  • Security and privacy issues raised by cookies
  • How to work with PHP sessions:
    • Starting a session
    • Storing information in a sessions
    • Ending a session

Part 1
HTTP Cookies

HTTP Cookies

  • Invented to provide continuity between visits to a web site.
    • HTTP: no long-term connection during a browsing session.
    • Cannot rely on IP address to provide identity.
  • Cookie is part of the HTTP header.
    • Transparent to user.
  • Cookies may be
    • temporary: expire when browser closes.
    • permanent: stored on client hard drive. (Still have expiration date.)
See the official IETF definition of cookies.

Set-cookie header

Form of a set-cookie HTTP header line:
Set-Cookie: name=value; expires=date; path=path; domain=domain-name; secure
  • name is like a variable name for the cookie.
  • value is the data stored in the cookie.
  • expires sets the expiration date.
    • If omitted, cookie expires when browser closes.
    • If in the past, existing cookie is deleted.
Total length including attributes should not exceed 4KB in length, normally much shorter.
Note: some less-used or less well-supported attributes are omitted for brevity. Explanations continued on next slide.

Set-cookie header, cont'd

  • path is the path on your server for which the cookie is valid.
    • "/" means the entire site.
    • If omitted, defaults to the path of the script that sets the cookie.
  • domain is the domain name for which the cookie is valid.
    • If omitted, defaults to domain of the script that sets the cookie.
    • Must be matching domain (same as script domain or contain it); browsers do not accept cookies belonging to other domains
  • secure if specified, cookie will only be sent over https.
Another security attribute, less well-supported:
  • httponly if specified, cookie data will not be made available through client side API, e.g. JavaScript.

Cookie protocol

  • Server sets cookie when returning response to normal request.
  • Client returns cookie name and value along with each request, if valid for domain and path.
    • Sent using a Cookie HTTP header.
    • Cookie attributes such as expires are not sent to the server.
  • Server recognizes cookie and acts according to contents.
    • “Remembers” the user.
    • Can provide continuity
      • during a continuous browsing session, or
      • (permanent cookies) between one visit and a later one.

Cookie header

  • Cookie is sent only if request matches domain of cookie, etc.
  • All valid cookies go in one Cookie header
  • Cookie header is sent by client along with request for a page. Form of header:
    • Single cookie:
      Cookie: cookie-name=value
    • Multiple cookies:
      Cookie: cookie-name=value; cookie-name=value ...

Setting a cookie in PHP

In PHP, set a cookie by
setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
  • Only $name is required.
    • To skip an argument (in order to provide an explicit one further on), replace:
      • strings by ""
      • integers by 0
  • Since cookie is sent in HTTP header, call must be placed prior to any output from the PHP including <html> tag or any whitespace.

Arguments of setcookie

  • $name -- string, the name of the cookie.
  • $value -- string, the value of the cookie.
  • $expire -- integer, expiration in Unix timestamp form (seconds since the epoch).
    • E.g. time()+3600 sets it to expire in 1 hour.
  • $path -- string, the path of validity.
  • $domain -- string, the domain of validity.
  • $secure -- boolean, use TRUE/1 or FALSE/0
  • $httponly -- boolean, use TRUE/1 or FALSE/0

Setting a cookie: example

This sets a session cookie:
<?php
setcookie("testcookie", "whatever");
?>
<html>
(Rest of page follows)

More examples

Assume
$name = "testcookie"; $value = "whatever";
  • Set a permanent secure cookie that expires in 30 days:
    setcookie($name, $value, time()+3600*24*30, "/~janeuser/", "dsm.fordham.edu", TRUE);
  • Set a session cookie while explicitly specifying path and domain:
    setcookie($name, $value, 0, "/~janeuser/", "dsm.fordham.edu");
  • Delete the cookie set in last example by setting time to the past:
    setcookie($name, "", time()-3600, "/~janeuser/", "dsm.fordham.edu");

Common pitfalls

  • Cookies do not become visible until next loading of a page for which cookie should be visible.
  • Cookies must be deleted with the same attributes provided when the cookie was sent. The value argument may be "" or FALSE.
  • Since a cookie value of FALSE means delete the cookie, if the cookie value is boolean use 0 and 1 as values.

Accessing cookies

Cookies received by server are in a superglobal:
  • $_COOKIE[$name] contains value of cookie named $name.
Example: visit this page first, before cookie is set:
Get cookie   PHP Code

Now set cookie, then return to the previous:
Set cookie   PHP Code

Example: signing in

  • Here is a more extended example, although still very primitive.
  • A visitor signs in to a web site and is then recognized upon return.
Sign in   PHP Code   Page 2 PHP
  • This example, unlike the previous one, uses a permanent cookie (expiration time 1 hour).
  • Try closing browser and then starting it again and re-visiting the page.

Cookies in JavaScript

  • It is possible to access cookies in JavaScript.
    • Exception: cookies with the httponly attribute
  • JavaScript can also set cookies.
    • This is kind of backwards since cookies are supposed to be set by the server
    • But there are cases where it is appropriate
      • E.g. remembering values of things JS sees, like form controls
  • Once set, cookie is returned to server same as if server had set it.
    • Server does not send cookie back to client.
    • But client saves cookie same as if server had set it.
      • So it is available on subsequent page visits to site.

JavaScript cookie API

  • Uses the document.cookie object.
    • API makes it look like a string
    • but a string with odd properties
  • Setting a cookie:
    document.cookie = "name=value"; // session cookie
    document.cookie = "name=value; expires=date";
    • Note: date is a UTC String not an integer
  • However:
    • Assigning a different string does not delete the existing cookie
      • it adds the new cookie to the set of cookies
      • to delete a cookie, assign with expiration date in the past

Reading cookies in JavaScript

  • The document.cookie object contains all cookies separated by semicolons
    • Use document.cookie.split("; ") to get list of cookie-value pairs.
Example:
document.cookie = "visitor=Alex";
document.cookie = "favecolor=blue"; // appends
window.alert(document.cookie);
Result:
visitor=Alex; favecolor=blue
(plus any other valid cookies floating around)

Setting cookies in JavaScript

Here is a simple example that sets a cookie based on a value entered by the visitor into a text box.

The cookie is set whenever the value in the box changes.

Set Cookie   HTML Code   JavaScript

JavaScript cookie operations

  • Here is a small JavaScript library to work with cookies:
Library   Test   HTML of test
  • Stepp et al text has a library of cookie functions
    • More fleshed-out than the above simple library
    • Defines a Cookie object with methods
    • See section 14.2.3 of the text for details

Proper use of cookies

The previous examples are bad practice: they store the user information (e.g. visitor name) in the cookie itself.
  • Limited data storage (4KB)
  • Lacks privacy
  • Vulnerable to manipulation by malicious client
Usually, cookie stores only
  • User ID
    or
  • Session ID
Used to key into database on server where further info is stored.

Third-party cookies

Definition: a third-party cookie is a cookie whose domain does not encompass the domain of the page setting the cookie.

Web browsers do not accept cookies whose domain attribute does not include the domain of the page. So how are third-party cookies set?
  • Page contains an element that is hosted on a different domain, and that element comes with a cookie from that domain. Examples:
    • Images for ads
    • Web bugs: small, inconspicuous images or iframes.

Tracking with third-party cookies

  • alpha.com serves page with embedded ad whose URL is on tracker.com.
    • Request for ad sets cookie with domain tracker.com.
    • Request includes Referer header identifying the page being visited at alpha.com.
  • User later visits beta.com which also includes ad provided by tracker.com.
    • Request that loads ad returns cookie set earlier to tracker.com
    • Referer identifes the page being visited at beta.com.
  • Now tracker.com has a list of pages visited by the user and can put them together.
    • In cooperation with Alpha and Beta, can pool data to link with other information they have about user.

Part 2
PHP Sessions

PHP Sessions

PHP Sessions provide a robust, easy-to-use API for maintaining continuity between accesses to the web site.
  • Like temporary cookies:
    • Session ends when browser is closed
    • Can end session sooner (like deleting cookie)
  • Simpler to use than cookies:
    • Details handled by API
    • Session data stored on server
    • Works even if cookies are disabled

How PHP sessions work

  • Visitor is assigned a unique session id. This is either
    • stored in a cookie, or (if visitor has disabled cookies and site allows)
    • propagated in the URL.
  • Session data is stored on server, keyed by session id.
  • API accesses it through $_SESSION superglobal array.
    • Data stored there persists between page views


View-Counter   PHP Code   nextpage PHP

Cookies vs URL based session

Best security with cookie method. From php.net:
Note: URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.
  • URL based sessions are disabled for dsm and default WAMP, enabled for default XAMPP.
  • Control this by setting session.use_only_cookies in php.ini
Version of view counter enabled for either cookies or URL based sessions:
View-Counter   PHP Code   nextpage PHP

Connecting to a session

  • Every page that is to participate in a session needs to include
    session_start();
  • Place this at top of page, before any output
  • Looks for existing session ID
    • If found, connects to it
    • If none, starts new session

Ending a session

  • End a session using session_destroy();
    • This clears all data associated with the session
    • It does not clear the session cookie
      • Not usually necessary, but if you want to...
      • Code for clearing session cookie is given at php.net
Destroy Session   PHP Code

Example: signing in

  • This example behaves like the earlier one using a cookie, but uses a PHP session instead.
  • All-in-one coding: code in one file, with tests determine which action to perform
Sign in   PHP Code   Page 2 PHP