PHP I : Cookies & Sessions

Follow this lesson in Ullman Chapter 9. The scripts are located in the 09 directory.


Creating Cookies

setcookie (‘cookie_name‘, ‘cookie_value‘);

or more formally:

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script. Do this by using output buffering.


Buffering header output for cookies

This must go ABOVE all other code, before the HTML declarations, before EVERYTHING:

// This starts output buffering

Then this must go BELOW all other code, after closing body and HTML declarations, after EVERYTHING:

ob_end_flush (); // Sends the page


Cookie values

A cookie can be as simple as:


or as complete as:

setcookie(‘username’, ‘Fred’, time()+60*60*24*30, ‘/’, ‘’, 1, 1);

For example:

// Set cookies

$visit=$visits + 1;
setcookie(“visits”, “$visit”,$exp);
echo “You have visited “.$_COOKIE[“visits”].” times”;


Reading Cookies


If you performed:

setcookie (‘user’, ‘user_name‘);

Then you could retrieve:

print $_COOKIE[‘user’];


if (isset($_COOKIE[‘user’])) {
  print $_COOKIE[‘user’];

When you set a cookie, it’s not available until the next page load occurs.


Cookie Parameters

setcookie ( ‘name‘, ‘value‘, ‘expiration‘, ‘path‘, ‘domain‘, ‘secure‘, ‘http_only‘)’

name – the cookie’s name; you may be setting more than one

expiration – (seconds since the epoch) – use time()+number_of_seconds, for instance:

$expire = time() + 60 * 60 * 24 * 30

path – limit to a specific folder on a web site

domain – limit to a specific domain

secure – limit to https connections (1) or not (0)

http_only – make cookie available for call only from http documents, not from JavaScript or PHP, for instance.


Deleting Cookies

If you:

setcookie (‘user’, ‘Fred’);


setcookie (‘user’, ”);

Or even more:

setcookie (‘user’, ‘Fred’, time() – 60);


To do out of class:

Review Chapter 9 of Ullman.