PHP: Cookies
Derek Bridge
Department of Computer Science,
University College Cork
PHP: Cookies
Aims:
- to know what people mean when they say that HTTP is a stateless protocol, and why this
can be a problem
- to know some of the solutions to this problem
- to understand how cookies work in detail and how to use them in PHP
- to know some of the issues with cookies
State management
- HTTP was designed for hyperlinked documents
- a client contacts a server and requests a document
- the server sends the requested document to the client
- HTTP is a stateless protocol
- each request is independent: by default, the server
has no memory of previous requests
- This approach is adequate for hyperlinked documents but often inadequate
for situations where it can be useful to recognise repeat contacts, e.g.:
- a client which has contacted the server in the past
- a sequence of requests from the same client within a short period of
time (a session)
Ways to achieve state management
There are many ways to detect that two requests come from the same client:
- IP addresses: keep a record of clients' IP addresses
- URL rewriting: include a user identifier in the query part of a URL
- Hidden fields: include a non-visible field in forms so that a user
identifier gets submitted with every request
- Cookies
Cookies for state management (simplified)
- A cookie is a small amount of data (a name/value pair)
- E.g.
id=cust123
- Each cookie can be no more than 4kb in size
- If a browser has sent a request to a server, the server can include a cookie
in its response (in a header line)
- If the browser has cookies enabled, it stores the cookie
- Next time the browser sends a request to the same server, it includes the cookie
in its request (a header line)
- This enables the server to know that it has previously received requests from
this client
Cookies example
- Your browser sends a request to
www.amazon.co.uk
:
GET /index.html HTTP/1.1
…
- The server stores information, e.g. in its database, about your visit
- The server's response includes a cookie:
HTTP/1.1 200 OK
Set-Cookie: id=cust123; path=/; domain=.amazon.co.uk
…
- If cookies are enabled in your browser, your browser stores the cookie
- On a subsequent occasion, you visit
www.amazon.co.uk
again
- Your browser includes the cookie in the request:
GET /index.html HTTP/1.1
Cookie: id=cust123
…
- The server now knows that you have made requests on previous occasions and
can use the cookie data, e.g. to look you up in its database
Two types of cookie: persistent and in-memory
- Persistent cookies:
- the server includes an expiry date in the cookie:
HTTP/1.1 200 OK
Set-Cookie: id=cust123; expires=Sun, 17-Jan-2039 19:14:07 GMT; path=/; domain=.amazon.co.uk
…
- the browser stores the cookie on the client's hard disk
- the browser deletes the cookie when it expires
- Persistent cookies are useful for identifying clients which have contacted the
server in the past
Two types of cookie: persistent and in-memory
- In-memory cookies:
- the server does not include an expiry date:
HTTP/1.1 200 OK
Set-Cookie: id=cust123; path=/; domain=.amazon.co.uk
…
- the browser stores the cookie in main memory
- the browser (ordinarily) deletes the cookie when
the browser is shut down
- In-memory cookies are useful for sessions
Cookies in PHP: sending them
- Suppose you want the output of your PHP script to include a cookie
- In your script, use the
setcookie
function
- The function can take seven parameters; only the first parameter is mandatory;
in simple scripts, the first three parameters are useful:
- name of the cookie
- value of the cookie
- the date and time at which it expires
- E.g.
setcookie( 'num_visits', $counter, time()+86400*365*5 );
- (The
time()
function returns the current time as seconds since midnight
1 Jan 1970 GMT)
Cookies in PHP: sending them
- If you want your PHP script to send a cookie, you must invoke
setcookie()
before any of the HTML is generated*
- E.g this will generate an error message:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My web page with a cookie</title>
</head>
<body>
<?php
setcookie( 'num_visits', $counter, time()+86400*365*5 );
?>
</body>
</html>
- This is because cookies are included in response header lines and these must be
finalized before you start to create the response body
(*unless PHP's output buffering is enabled, which it is not in our installation)
Class exercise
Assume these show the first few lines of various PHP scripts.
Which of them give error messages?
-
<?php
output_header( 'My web page with a cookie', 'stylesheet.css' );
setcookie( 'num_visits', $counter, time()+86400*365*5 );
?>
-
<?php
setcookie( 'num_visits', $counter, time()+86400*365*5 );
?>
-
<?php
setcookie( 'num_visits', $counter, time()+86400*365*5 );
?>
Cookies in PHP: accessing them
- Your PHP script can find out whether the browser has sent it any cookies and, if it has,
can access cookies using one of PHP's superglobals:
$_COOKIE
- It works just like the
$_GET
and $_POST
arrays
- E.g. you can test whether the browser has sent you a cookie called
num_visits
as follows:
if ( isset($_COOKIE['num_visits']) ) ...
- Class exercise Why might it not be set? (Several reasons)
counter.php
: a simple example
Counting the number of times a page has been accessed by a client
<?php
require_once( 'output_functions.php' );
if ( ! isset($_COOKIE['num_visits']) )
{
$counter = 1;
}
else
{
$counter = $_COOKIE['num_visits'] + 1;
}
setcookie( 'num_visits', $counter, time()+86400*365*5 );
output_header( 'Welcome!', 'stylesheet.css' );
output_paragraph( "You have visited this page {$counter} times" );
output_footer( 'University College Cork' );
?>
Some of the issues with cookies
- Accuracy in identifying the user
- If you use more than one machine or more than one browser on the
same machine, you will have separate cookies, so the server may
think you are two different people
- If you share an account and a browser on a machine with someone, you will
have the same cookies, so the server may think you are one person
- Violations of privacy
- They can be used to track the pages you visit within a site
- Do you want the owners of the site to know this?
- Should they be allowed to sell on this information?
- Third-party cookies
- Suppose you request a web page that contains an image (e.g. an ad) that's stored on another site
- Then your browser will request that image from that site
- That site will probably set a cookie: a third-party cookie
- Advertising companies such as doubleclick.com do this all the time
- Effectively, they are tracking your visits across all sorts of sites, wherever
they place their ads
- Is this an even bigger violation of your privacy?
- Cookie theft (a.k.a session hijacking)
- Network traffic can be intercepted
- Passwords and credit card details are usually sent using SSL (hence, encrypted)
- Cookies generally aren't!
- Either use HTTPS (HTTP+SSL) or never send sensitive information in a cookie