Main Page

Passing cookies between client and server

The one restriction on setting cookies in PHP is that it must be done before anything is output to the
client. This is similar to the way the
header()
function works. For instance, this code won’t work:
<html>
<head>
<?php
setcookie(“name”, “Nicholas”);
setcookie(“book”, “Professional JavaScript”);
?>
To retrieve the value of a cookie in PHP, use the
$_COOKIE
associative array with the name of the cookie
as the key:
<?php
$name = $_COOKIE[“name”];
$book = $_COOKIE[“book”];
?>
Note that you cannot retrieve the value of a cookie created with
setcookie()
until the next page loads,
meaning that is the following code is impossible:
<?php
setcookie(“name”, “Nicholas”);
setcookie(“book”, “Professional JavaScript”);
$name = $_COOKIE[“name”];
$book = $_COOKIE[“book”];
?>
To delete a cookie in PHP, just use the
setcookie()
method and set the expiration time to
0
:
<?php
setcookie(“name”, “”, 0);
?>
Passing cookies between client and server
To communicate to JavaScript, often the server creates a cookie (perhaps in a servlet or other application
running on the server) just before a response is sent out. The page that is loaded now has JavaScript
designed to retrieve the cookie value.
For example, suppose you are creating a feedback form on a Web site where the user is required to enter
a name, e-mail address, and the feedback message. You can make this more user-friendly by allowing
the users to save their names and e-mail addresses so the next time they visit and want to leave feed-
back, both fields are already filled in. Typically, you do this with a Remember Me check box, as in the
following form:
<form name=”feedbackForm” method=”post” action=”submitfeedback.php”>
<p>Name: <input type=”text” name=”personName” /><br />
E-mail Address: <input type=”text” name=”personEmail” /><br />
488
Chapter 16
19_579088 ch16.qxd 3/28/05 11:42 AM Page 488


JavaScript EditorFree JavaScript Editor     Ajax Editor


©