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:

<?php
ob_start();
// This starts output buffering
?>

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

<?php
ob_end_flush (); // Sends the page
?>

 

Cookie values

A cookie can be as simple as:

setcookie(‘mycookie’,’value’);

or as complete as:

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

For example:

<?php
// Set cookies

$visit=$visits + 1;
$exp=time()+365*24*60*60;
setcookie(“visits”, “$visit”,$exp);
echo “You have visited “.$_COOKIE[“visits”].” times”;
?>

 

Reading Cookies

$_COOKIE

If you performed:

setcookie (‘user’, ‘user_name‘);

Then you could retrieve:

print $_COOKIE[‘user’];

Or:

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’);

Then:

setcookie (‘user’, ”);

Or even more:

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

 

To do out of class:

Review Chapter 9 of Ullman.