PHP cookie

What are cookies

A cookie is a small text file saved by web server on the visitor computer. In internet you often see a check box with text "remember me in this computer" below a login form. The method it uses to remember the user is to set cookie to the user computer. When browser requests the login page again it also sends the previously saved cookie too. Server reads that cookie and directly logs you into your account. This is a very common example of use of cookie. You can use cookies for any purpose, such as you can use them to pass variables among the pages. But remember that do not use cookie to store any sensitive information like credit card number, etc, because they are stored in user computer, not in your secured database, understanding identity theft in the USA will help you avoid some common mistakes like that.

In short purposes of the cookies are,

  1. Save important information about the user, e.g. user name, email address etc.
  2. Passing variables among the pages.

Properties of cookies

A cookie has the following properties.

Cookie domain:

The domain name which creates the cookie. Two points you must remember about cookie domain that (i) you can't create a cookie with other domain name say www.google.com or www.microsoft.com; and (ii) domain name with or without www are considered as different domain. So you should put domain name ".yourdomain.com" such that cookie becomes available all sub domains under your domain with or without www.

Cookie name:

The name of the cookie by which it will be identified. You require this name identifier when you read or write to the cookie.

Cookie value:

This is the data which you store into a cookie.

Cookie expires:

The date after which the cookie will be expired. The date format is DD-Mon-YYYY HH:MM:SS UTC. If you omite this argument cookie will be expired after current session.

Cookie path:

Path in which the cookie will be available. If path='/' then cookie will be global cookie within this domain. If you do not mention path then by default it will be the path of the current page creating cookie, i.e. if I create cookie from page http://ramui.com/articles/thispage.html without mentioning the path, cookie will be available under path ramui.com/articles/ and all of its sub-directory. Here path = '/articles/'.

Secure:

Secure flag indicates that the cookie should only be transmitted over a secure HTTPS (SSL) connection from the client.

httponly:

When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectly help to reduce identity theft through XSS attacks (although it is not supported by all browsers).

PHP cookies:

In PHP cookie can be read with the following command.
$cookie=$_COOKIE['cookiename'];

PHP setcookie():

To create a cookie use PHP function setcookie(). This function takes following arguments.

bool setcookie ( string name , string value , int expire , string path , string domain , bool secure , bool httponly).

The following points you should remember about this function:
1. All arguments but name are optional.
2. Instead of prescribed date format the expire parameter takes UNIX timestamp. Actually PHP internally convert it to the date format.

Example of creating cookie in PHP

In the following example we shall create a cookie named testcookie which will be expired one month after creation.

Code | Download
<?php
//Create UNIX timestamp for one month from now.
$expire=time()+30*24*60*60;
if(setcookie('testcookie','cookie example',$expire,'/','.ramui.com',false,true)){
//If condition return true if cookie is successfully created.
echo 'testcookie has been successfully created.';}
?>

Storing multiple data in one cookie

You can store multiple data in one cookie by using string separator. In the following example I store user name and email address in one cookie named userdata'.

Code | Download
<?php
$user=$_POST['user'];
$email=$_POST['email'];
//Create UNIX timestamp for one month from now.
$expire=time()+30*24*60*60;
setcookie('userdata',$user.'||'.$email,$expire,'/','.ramui.
com',false,true);
?>

Here I add a new string '||' as string separator. While selecting such a separator we must confirm that data itself not contain that string. Now in the following code we will see how to retrieve data from such a cookie.

Code | Download
<?php
//Check whether any valid cookie is there.
isset($userdata=$_COOKIE['userdata']){
$arr_userdata=explode('||',$userdata);
$user=$arr_userdata[0];
$email=$arr_userdata[1];}
?>

Expire or delete cookie

To delete or reset a cookie use PHP setcookie() function. The following command will delete cookie 'userdata'.

<?php setcookie('userdata'); ?>

Alternatively you can force cookie to expire by setting expire date before the current date. So the following command will expire the cookie 'userdata'.

<?php setcookie('userdata','',(time()-3600)); ?>

Applications and disadvantages of cookies:

  1. A cookie can be used in identifying user irrespective to the IP address it provides.
  2. A cookie can be used to pass variables among the pages. If you set cookie path at the root of your domain (path='/') the data stored in the cookie will be globally available. In this way you can use a cookie for session management. Alternatively you can set cookie path to a particular directory to restrict the variable scope within that directory.
  3. You can use cookie to offer users to personalize the appearance of your web page. You may notice in some popular forum script (e.g. SMF) user can personalize the appearance by choosing template of their choice. They actually store your preferences in a cookie file in your computer.
  4. As cookies are stored in user computer there is always a security risk in protecting them. You should take extra caution like data encryption, before storing any sensitive data in a cookie.
  5. Cookie will not be available if user opens your site from different browser even in the same computer. Also users have the option to delete cookies from their computer. So you can never be certain in identifying users through cookies.
  6. You will be unable to store cookie if user doesn't allow your domain to store any cookie.

PHP cookie example

Here is a PHP cookie example in practical application. You often see the text "rate this article" below an internet article. When a new viewer read it and rates the article by clicking a command button on it the web server takes the following steps.

  1. Server reads whether any cookie is already stored for that viewer.
  2. Set a cookie of unique value for future identification of the viewer. The lifetime of this cookie is usually very long from six months to one year.
  3. The rating of the viewer, user identifier which stored in form of cookie and the article identifier which is usually article ID is stored in database.
  4. Send a "thank you" message to the viewer.

In future when that viewer tries to rate the same article server reads the cookie and search the database whether that viewer already rate that particular article or not. When it found that the article is already rated then server ignores the rating and delivers appropriate message to the viewer.

In few systems server initially reads the cookie when the page is requested and disables the rating button to prevent further voting.

Points to remember about cookies:

Here are some useful points you should remember about cookies.

  1. A cookie is a text file. So it can't store virus or any other malicious elements in your computer.
  2. A cookie can't generate any popup ad or spam email for you.
  3. As a webmaster do not depend too much on cookies. Keep your site active with or without cookie.
  4. Limit max size of a cookie below 4kb and max no of cookie below 20.
Comments:

How to block cookies in Mozilla Firefox

COMMENT BY: clanR DATE: Jul 19, 11:32
Fantastic article! I've one question, how can i prevent cookie from a particular site? I'm using Mozilla Firefox.

Reply: How to block cookies in Mozilla Firefox

COMMENT BY: admin DATE: Jul 19, 11:37
Thank you for reading my article.
In Mozilla Firefox open Option dialog box by clicking Tool -> Option menu.
Select the privacy tab from top of the dialog box. Under Cookie group box check the opton Accept cookies from the sites.
Now Add exceptions for the sites for which you do not want to accept cookies. That's all.

JavaScript cookie

COMMENT BY: noname DATE: Jul 31, 08:35
Can I manipulate cookie created by PHP from server end with JavaScript?

Manipulate PHP cookie with JavaScript

COMMENT BY: admin DATE: Jul 31, 08:38
You can manipulate cookie created by PHP with JavaScript, on condition that the httponly flag of setcookie function argument must be kept false.

thanks for article

COMMENT BY: sachin DATE: Jan 04, 09:11
I have cleared me so much about cookies , that why and how to use it.Awesome.....

thanks for article

COMMENT BY: sachin DATE: Jan 04, 09:12
IT has cleared me so much about cookies , that why and how to use it.Awesome.....

Add comment