Using Cookies in PHP

By: Andi, Stig and Derick  

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:








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


} else {



<form method="post" action="login.php">


<tr><td>E-mail address:</td>

<td><input type='text' name='email'/></td></tr>


<td><input type='password' name='password'/></td></tr>

<tr><td colspan='2'>

<input type='submit' name='login' value='Log in'/></td>








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, the cookie is available to all subdomains of Or, you could use, 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:


if (isset ($_COOKIE['uid']) && $_COOKIE['uid']) {



<head><title>Index page</title></head>


Logged in with UID: <?php echo $_COOKIE['uid']; ?><br />

<a href='logout.php'>Log out</a>.




} 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:


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.


Archived Comments

1. Darinfaf
View Tutorial          By: Darinfaf at 2017-08-12 21:14:40

Most Viewed Articles (in PHP )

instanceof OPERATOR in PHP

Encrypting files using GnuPG (GPG) via PHP

Using class within a function in PHP

Using Text-File Databases in PHP

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/ into server:

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Function to force strict boolean values in PHP

Function to convert strings to strict booleans in PHP

Function to sort array by elements and count of element in PHP

Malware: global $ob_starting;

Latest Articles (in PHP)

Comment on this tutorial