Page 169 - Open Soource Technologies 304.indd
P. 169
Open Source Technologies
Notes anything about your previous visits. A cookie is a mechanism that allows the server to store its
own information about a user on the user’s own computer. You can view the cookies that have
been stored on your hard disk (although the content stored in each cookie may not make much
sense to you). The location of the cookies depends on the browser. Internet Explorer stores each
cookie as a separate file under a Windows subdirectory. Netscape stores all cookies in a single
cookies.txt. Opera stores them in a single cookies.dat file.
10.1 Cookies
Cookies are commonly used to rotate the banner ads that a site sends so that it doesn’t keep
sending the same ad as it sends you a succession of requested pages. They can also be used
to customize pages for you based on your browser type or other information you may have
provided the Web site. Web users must agree to let cookies be saved for them, but, in general, it
helps Web sites to serve users better. A server can set as many as 20 cookies, and each of these
cookies can be up to 4 KB in size.
The simple registration we used earlier in this chapter does not make data persistent across
requests. If you go to the next page (such as by clicking a link or by entering a different URL in
your browser’s address bar), the posted data is gone. One simple way to maintain data between
the different pages in a web application is with cookies. Cookies are sent by PHP through the
web servermn with the setcookie() function and are stored in the browser. If a time-out is set for
the cookie, the browser will even remember the cookie when you reset your computer; without
the time-out set, the browser forgets the cookie as soon as the browser closes. You can also set
a cookie to be valid only for a specific subdomain, rather than having the cookie sent by the
browser to the script whenever the domain of the script is the same as the domain where the
cookie was set (the default). In the next example, we set a cookie when a user has successfully
logged in with the login form
<?php
ob_start();
?>
<html>
<head><title>Login</title></head>
<body>
<?php
if (isset ($_POST[‘login’]) && ($_POST[‘login’] == ‘Log in’) &&
($uid = check_auth($_POST[‘email’], $_POST[‘password’])))
{
/* User successfully logged in, setting cookie */
setcookie(‘uid’, $uid, time() + 14400, ‘/’);
header(‘Location: http://kossu/crap/0x-examples/index.php’);
exit();
164 LOVELY PROFESSIONAL UNIVERSITY