Page 171 - Open Soource Technologies 304.indd
P. 171
Open Source Technologies
Notes available to all subdomains of example.com. Or, you could use admin.example.com, restricting
the cookies to the admin part of your application. In this case, we did not specify a domain,
so all pages in the web application receive the cookie. After the line with the setcookie() call, a
line issues a redirect header to the browser. This header requires the full path to the destination
page. After the header line, we terminate the script with exit() so that no headers can be set
from later parts of the code. The browser redirects to the given URL by requesting the new page
and discarding the content of the current one. On any web page requested after the script that
called set_cookie(), the cookie data is available in your script in a manner similar to the GET
and POST data. The superglobal to read cookies is $_COOKIE. The following index.php script
shows the use of cookies to authenticate a user. The first line of the page checks whether the
cookie with the user id is set. If it’s set, we display our index.php page, echoing the user id set
in the cookie. If it’s not set, we redirect to the login page:
<?php
if (isset ($_COOKIE[‘uid’]) && $_COOKIE[‘uid’]) {
?>
<html>
<head><title>Index page</title></head>
<body>
Logged in with UID: <?php echo $_COOKIE[‘uid’]; ?><br />
<a href=’logout.php’>Log out</a>.
</body>
</html>
<?php
} else {
/* If no UID is in the cookie, we redirect to the login
→page */
header(‘Location: http://kossu/examples/login.php’);
}
?>
Using this user id for important items, such as remembering authentication data (as we do in
this script), is not wise, because it’s easy to fake cookies. (For most browsers, it is enough to
edit a simple text field.) A better solution—
using PHP sessions—follows in a bit.
Deleting a cookie is almost the same as setting one. To delete it, you use the same parameters
that you used when you set the cookie, except for the value, which needs to be an empty string,
and the expiry date, which needs to be set in the past. On our logout page, we delete the cookie
this way:
<?php
setcookie(‘uid’, ‘’, time() - 86400, ‘/’);
166 LOVELY PROFESSIONAL UNIVERSITY