Using Cookies in PHP

By: Andi, Stig and Derick Viewed: 153285 times  Printer Friendly Format    


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 server 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();

} else {

?>

<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 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—.

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, '/');

header('Location: http://kossu/examples/login.php');

?>

The time() - 86400 is exactly one day ago, which is sufficiently in the past for our browser to forget the cookie data.

 



Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial