INTRODUCTION TO PHP AND MYSQL - WORKING WITH COOKIES

In the exercise, you will be working within the IntroductiontoPHP folder. If you have not already done so, create a new Dreamweaver site pointing to the IntroductiontoPHPfolder. You will need to add Remote Info and Testing Server information, and create a new folder on the server Introduction_to_PHP to which you will publish.

As we have mentioned, the web is a statelessprotocol. In other words, it forgets everything about the client and all information associated with it after every connection. Developers face the challenge of making values persist between connections. For example, in prior exercises, a user entered a name in a form and PHP returned a personalised response. Perhaps you would like all of the pages the user requests from your website to return the same personalised greeting - even on future visits. Saving the user’s name between connections is an example of maintainingstate.

Cookies enable your PHP pages to store one or more variable name and value pairs by writing them to small text files on the user’s computer. Your PHP pages can later retrieve these variable name and value pairs, even if the user has exited and restarted the browser in the interim. Cookies make it possible to share data across multiple page requests.

Cookies and Privacy

Because cookies are written as text to the user’s computer, there are questions about how secure this information may be. By default, a cookie that is set can be retrieved over the web only by a page from the same domain as the page that set the cookie. As we will see, it is also possible to set values for cookies that further restrict how they can be retrieved, their longevity and expiration date and whether they will be transmitted to the sever in an encrypted format. However, because cookies reside as text files on the local client computer anyone could conceivably sit down at the client computer and, if they know where to look, snoop in someone’s cookies. Because of this, it is inadvisable to store confidential information - like credit card numbers or social security numbers - in cookies.

Setting a Cookie

The setcookie function sets a cookie. It takes several arguments. The documentation below is from

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

Parameter / Description / Examples
name / The name of the cookie. / 'cookiename' is called as $_COOKIE['cookiename']
value / The value of the cookie. This value is stored on the client’s computer. Do not store sensitive information. / Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']
expire / The time the cookie expires. This is a Unixtimestamp so is in number of seconds since the epoch. In other words, you will most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). / time() + 60 * 60 * 24 * 30 will set the cookie to expire in 30 days. If not set the cookie will expire at the end of the session - when the browser closes.
path / The path on the server in which the cookie will be available on. / If set to '/' the cookie will be available within the entire domain. If set to '/foo/' the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar of domain. The default value is the currentdirectory that the cookie is being set in.
domain / The domain that the cookie is available. / To make the cookie available on all subdomains of example.com then you would set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to will make the cookie only available in the www subdomain.
secure / Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to TRUE the cookie will only be set if a secure connection exists. The default is FALSE. / 0 or 1

Warning: It is crucial to note that you must set cookies before any output is sent to the browser, including <!DOCTYPE> and other initial tags or whitespace. This is because cookies are part of the httpheaders. If you really do not want to do this, you can force your server to buffer output. This makes your server operate less efficiently - so do so with care. See details.

The Life Cycle of a Cookie

Retrieving a Cookie

You can retrieve values with the global $_COOKIE variable. A very simple demo is found in the files below.

Page 1 (demos/cookie-set.php)

<?php $cookie = setcookie("name","Joe",time()+60*60*24*7);?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Setting a Cookie</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>

<body>

<?php

if ($cookie) echo "Cookie set";

else echo "Cookie not set";

?>

</body>

</html>

Page 2 (demos/cookie-get.php)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Retrieving a Cookie</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>

<body>

<?php

if (isset($_COOKIE["name"])) echo "Hello " . $_COOKIE["name"];

else echo "No cookie set yet.";

?>

</body>

</html>

Example: Setting, Retrieving and Expiring a Cookie

The following demonstration uses three files to demonstrate cookies -cookiedemo.php, makecookie.php and killcookie.php. Ensure that all three files are published to the server.

First, request the filedemos/cookiedemo.phpfrom the server. The following screen is displayed:

Completing and submitting the form requests makecookie.php which contains the code that sets the name in a cookie named firstName on your local computer

Following the link back to cookiedemo.php (or just clicking the Back button and refreshing) will display this page.

The cookie will persist even if the browser is closed and relaunched. Therefore future requests for cookiedemo.php will continue to retrieve the cookie and return a personalised response.

Click the clear this cookie link to request killcookie.php the file that expires the cookie.

Explanation of the code

Requesting cookiedemo.php in the above case will return the form. The file cookiedemo.php shown below is a self-submitting file containing both a form and a response. Here, the conditionalstatement that nests the two blocks of code checks whether the cookie firstName exists on the local client computer. If it does, a customised greeting including information from the cookie is returned. If the cookie returns an empty string the form is returned.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Cookie Demonstration</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>

<body>

<?php if (isset($_COOKIE["firstName"]))

{

echo '<h1>Welcome back, ' . $_COOKIE["firstName"] . '!</h1>

<p>If you\'d like, you may <a href="killcookie.php">clear this cookie</a>. </p>';

}

else

{

?>

<h1>Welcome to our site!</h1>

<form action="makecookie.php" method="post">

<p>Please tell us your name:

<input type="text" name="firstName" />

<input type="submit" />

</p>

</form>

<?php

}

?>

</body>

</html>

When the form is submitted to makecookie.php this file sets the cookie firstName with the value retrieved from the form - and it sets an expiration date 365 days from the current date. Notice that the cookie is set before the HTML is sent to the browser. A link also sends the user back to cookiedemo.php. Here is the code for makecookie.php:

<?php

setcookie("firstName",$_POST["firstName"],time()+60*60*24*365);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Create Cookie</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>

<body>

<h1>Cookie has been set.</h1>

<h2<a href="cookiedemo.php">Return to cookie demonstration</a>.</h2>

</body>

</html>

If the cookie has been set, the greeting portion of cookiedemo.php provides a link to killcookie.php - allowing the client to voluntarily delete the cookie. This is done by setting the value of the cookie to an empty string (""). For good measure, we also set the expiration to a time in the past. Here is the code for killcookie.php:

<?php setcookie("firstName","",time() - 10); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<title>Delete Cookie</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>

<body>

<h1>Cookie has been deleted.</h1>

<h2<a href="cookiedemo.php">Return to test page</a>.</h2>

</body>

</html>

A - Introduction to PHP and MySQL - Working with Cookies

Page 1 of 9Version 1