Using Cookies in PHP

By: Andi, Stig and Derick Emailed: 1697 times Printed: 2200 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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.

 


PHP Home | All PHP Tutorials | Latest PHP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Andi, Stig and Derick
Execution Lifetime of a PHP script
preg_split() and explode() in PHP
preg_replace() and preg_replace_callback() in PHP
preg_match(), function preg_match_all(), preg_grep() in PHP
tmpfile() in PHP
Renaming and Removing Files in PHP
Locking files in PHP
File Handling in PHP
Handling BLOB in PHP and MySQL
Using Sessions in PHP
Using Cookies in PHP
Using PEAR::Crypt_HMAC in PHP
Using HMAC Verification in PHP
Input Validation in PHP
__autoload() METHOD in PHP

More Tutorials in PHP
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Convert XML to CSV in PHP
Password must include both numeric and alphabetic characters - Magento
PHP file upload (Large Files)
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Handling file locks in PHP
HTML table output using Nested for loops in PHP
Count occurrences of a character in a String in PHP

More Latest News
Most Viewed Articles (in PHP )
isset() function in PHP
Convert IP address to integer and back to IP address in PHP
Traversing Arrays Using foreach in PHP
public, protected, and private Properties in PHP
Using Cookies in PHP
preg_split() and explode() in PHP
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Parent: child process exited with status 3221225477 -- Restarting
Using Text file as database in PHP
Function to return number of digits of an integer in PHP
Get the first and last day of the month in PHP
Multiple File Upload in PHP using IFRAME
Convert XML to CSV in PHP
The Object (compound) Type in PHP
Traversing Arrays Using list() and each() in PHP
Most Emailed Articles (in PHP)
Traversing Arrays Using foreach in PHP
preg_split() and explode() in PHP
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Sorting an Array in PHP
fixEncoding in PHP
Assignment operators in PHP
switch Statements in PHP
preg_match(), function preg_match_all(), preg_grep() in PHP
Reading .CSV file in PHP
Encrypting files using GnuPG (GPG) via PHP
Where does the PHP run?
Setting up PHP in Windows 2003 Server IIS7, and WinXP 64
Perl's Encoding::FixLatin equivalent in PHP
break out of an if() block in PHP
PHP file upload with IIS on windows XP/2000 etc