Page 170 - Open Soource Technologies 304.indd
P. 170
Unit 10: Cookies
} else { Notes
?>
<h1>Log-in</h1>
<form method=”post” action=”login.php”>
<table>
<tr><td>E-mail address:</td>
<td><input type=’text’ name=’email’/></td></tr>
<tr><td>Password:</td>
<td><input type=’password’ name=’password’/></td></tr>
<tr><td colspan=’2’>
<input type=’submit’ name=’login’ value=’Log in’/></td>
</tr>
</table>
</form>
<?php
}
?>
</body>
The check_auth() function checks whether the username and password match with the stored
data and returns either the user id that belongs to the\ user or 0 when an error occurred. The
setcookie(‘uid’, $uid, time() 14400, ‘/’); line tells the web server to add a cookie header to send
to the browser. uid is the name of cookie to be set and $uid has the value of the uid cookie.
The expression time() + 14400 sets the expiry time of the cookie to the current time plus 14,400
seconds, which is 4 hours. The time on the server must be correct because the time() function is
the base for calculating the expiry time. Notice that the ob_start() function is the first line of the
script. ob_start() turns on output buffering, which is needed to send cookies (or other headers)
after you output data. Without this call to ob_start(), the output to the browser would have
started at the <html> line of the script, making it impossible to send any headers, and resulting
in the following error when trying to add another header (with setcookie() or header()): Instead
of using output buffering (which is memory-intensive), you can, of course, change your script
so that data is not output until after you set any headers. Cookies are sent by the script/web
server to the browser. The browser is then responsible for sending the cookie, via HTTP request
headers, to all successive pages that belong to your web application. With the third and fourth
parameters of the setcookie() function, you can control which sections of your web site receive
the specific cookie headers. The third parameter is /, which means that all pages in the domain
(the root and all subdirectories) should receive the cookie data. The fourth parameter controls
which domains receive the cookie header. For instance, if you use .example.com, the cookie is
LOVELY PROFESSIONAL UNIVERSITY 165