PHP Cookies : Tutorial on how to get and set cookie using PHP

A cookie is small chunk of data stored in user’s browser for a specific website. Website sent instruction to create a cookie on the browser using response HTTP header. Also once cookie get created, browser send the cookie information in request HTTP header. In this tutorial we will discuss complete concept of the cookie. As the the tutorial title is  PHP Cookie we will also dive in detail to set,get and delete cookie using PHP script.

php-cookie

What is cookie

As per the Wikipedia definition of cookie is below:

A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user’s web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user’s previous activity.

In simple word cookie is the very small chunk of data we can sent to the server and received to the browser using HTTP HEADER. First time server sent the cookie information to the browser and browser stores the cookie name and the value associated with cookie. After that whenever a new request made to that site through the same browser, browser sends that cookie information to server subjected on the validity. Validity of the cookie depend upon several factor like the expiry date, path etc. We will discuss the validity factor later in this chapter.

So Cookies are used to track or identify the returning user and user information.

Validity of Cookie

Validity of the cookie depends upon following four parameters.

  1. Path : Cookie always valid for a particular path. For example if we have created cookie for path /user/ , then we can only access cookie from path /user/ and its child like /user/1 /user/username/edit etc.
  2. Expiration Time : While creating the cookie we send expiration time, or when the cookie value will be expire.
  3. HTTP Only : This parameter is used for security reason. If you do not want your cookie to be accessible from JavaScript you can make your cookie HTTP Only. Or in other word HTTP only cookies can be accessible from HTTP protocol. This is not exactly the validity point for server side languages. It is point of validity for browser scripting languages like JavaScript.
  4. Secure : When this parameter is on/active cookie will only be accessible from secure connection. Means if the parameter is true cookie will be accessible from HTTPS protocol.

How to verify cookie information in your browser

Before going into much detail to explore how to create/update/delete cookie using PHP script, It is important to know how to see the cookie value in browser.  Here we will discuss how to see cookie in Chrome and Firefox browser.

Cookie in Chrome : To see the cookie stored by any website in chrome follow the following steps:

  1. Open the website for which you need to see the cookie.
  2. Please go to Menu -> Tool ->Developer Tool or press F12 button.
  3. It will open the developer tool box.(below is the screenshot )chrome_cookie (1)
  4. Now click on the Resource Button in the developer tool from top menu.
  5. Once you will click the resource button, left panel of the developer tool bar will show all of the resources.
  6. Click on the cookie button. It will show all the domain.
  7. From the domain click on the domain for which you want to see the cookies.
  8. On Right panel all cookies and their related information will be displayed.

Cookie in Mozila Firefox : To see cookie in Mozilla Firefox follow the below steps:

  1. Open the website for which you need to track the cookie.
  2. Go to Tool -> Option and click on Privacy Tab.
  3. Here Click on the remove Individual Cookie link.
  4. Now popup window will appear with all cookie.
  5. Search for your domain.firefox-cookie

PHP and Cookies

PHP support HTTP Cookies. We can create/update or remove cookies with the help of PHP functions.

Cookie information is sent in the http header, so cookie should always be created  before sending any content. Otherwise php will throw error of header already sent.

We can create/edit/delete cookie in PHP by using header() function with passing the valid HTTP cookie header string.  Also PHP has built-in function setCookie and setrawcookieto create/edit/delete cookie.

So before going into much detail to create/edit/delete cookie let us review the HTTP request and response header with HTTP cookie.

Below is the example of the HTTP response header which has cookie information

HTTP/1.1 200 OK
Date: Tue, 02 Sep 2014 01:26:00 GMT
Server: Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9
X-Powered-By: PHP/5.2.9
Set-Cookie: testcookie=testval; expires=Wed, 03-Sep-2014 11:23:02 GMT; path=/
Content-Length: 1
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

Below is the HTTP header request after cookie is created on browser:

GET /test/cookie/1.php HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6
Cookie: testcookie=testval

PHP header() function and cookie

In php using header function we can pass HTTP header request. Now as you can see in the above HTTP header request that to create HTTP cookie on browser we need to pass below http header request:
Set-Cookie: testcookie=testval; expires=Wed, 03-Sep-2014 11:23:02 GMT; path=/
So if we will pass above http header using php header function then cookie will be created with name testcookie.Below is the code example
<?php
header('Set-Cookie:testcookie=testval; expires=Sat, 23-Sep-2014 11:23:02 GMT; path=/');
echo 'PHP cookie is created using header function';
?>

In above example we are passing complete cookie HTTP header using php header function. Here we are passing the expiry date and path.

To edit the cookie value we only need to change the value in the http header. Example:
header('Set-Cookie:testcookie=testval1; expires=Sat, 23-Sep-2014 11:23:02 GMT; path=/');

To delete the cookie we only need to change the expiry date of cookie to past. Example:
header('Set-Cookie:testcookie=testval1; expires=Sat, 23-Aug-2014 11:23:02 GMT; path=/');

We can pass different type of HTTP request header using php header function. However to create cookie we should use php setCookie and setRawCookie function. Because PHP handle all cookie string concatenation and GMT time conversion by default in these method.

PHP setCookie and setRawCookie method to create Cookie

SetCookie and SetRawCookie are built-in method to create/edit/delete cookie in php. Both do the same thing(manipulation of cookie), but in setCookie method your cookie value will be url encoded but in setrawcookie your cookie value will not be url encoded. Both method also takes the same number and type of parameters. So here will will demonstrate all example using setCookie.

To create/edit/delete cookie using setCookie method we need to pass below parameter:

  1. Name : Name of the cookie
  2. Value : Value of the cookie
  3. Expiry : Expiry date of the cookie. Expiry will be the unix timestamp. We can use time function. So if we need to store cookie for 1 hr then we need to pass time() + 60*60. To delete the cookie we need to pass expiry date in past. Example time() – 1000.
  4. Path : Path where cookie will be accessible. If we will pass / the cookie will be available for entire domain. If we will pass domain /test/ then cookie will be available to yourdomain.com/test/ and its sub directory.
  5. Domain Name : You can pass domain in which your cookie will be available. If we will past yourdomain.com in the domain then it will be availabe in all subdomain of yourdomain.com ex www.yourdomain.com or ww2.yourdomain.com. But if you will pass www.yourdomain.com in the domain then it will only be available for www.yourdomain.com. Not for ww2.yourdomain.com
  6. Secure : This is boolean parameter. If you will set it true then your cookie will be accessible through HTTPS url only.
  7. HTTPonly : This is again a boolean parameter. If you will set it true then your cookie will be accessible through http protocall only. In other word, you can not access your cookie through javascript of the paramter is set true.

Example of creating cookie using setCookie method:
<?php
setcookie('testcookie', 'testval', time() + 122222, '/' , 'localhost' , false , true);
echo 'php cookie is created using setcookie method';
?>

If you need to delete the cookie you can pass expiry time in past. Ex
<?php
setcookie('testcookie', 'testval', time() - 122222, '/' , 'localhost' , false , true);
echo 'php cookie is created using setcookie method';
?>

Accessing Cookie value in php

You can access cookie in your php code using super global variable $_COOKIE. Cookie value is also available in $_REQUEST and $HTTP_COOKIE_VARS.

Cookie value can only be accessible in the just next request of the cookie creation. This is because in the first request you sent HTTP header to your browser to store the cookie information. Now from the next browser request browser sent the cookie name and the value till the time it is not expire.

For example:
<?php
print_r($_COOKIE); //accessing php cookie using $_COOKIE
print_r($_REQUEST); //Accessing php cookie using $_REQUEST.
print_r($HTTP_COOKIE_VARS); //accesing php cookie usng $HTTP_COOKIE_VARS
?>

Download complete code of this tutorial.

To read Further more about cookie please refer below URL:http://en.wikipedia.org/wiki/HTTP_cookie