Cookies in PHP

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.  This blog will teach you how to set cookies, how to access them and how to delete them.

You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

How to use Cookie

Cookies are usually set in an HTTP header ( JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers:

HTTP/1.1 200 OK
Date: Fri, 22 Feb 2014 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/5.03
Set-Cookie: name=xyz; expires=Friday, 22-Feb-14 22:03:38 GMT;
path=/; domain=astemplates.com
Connection: close
Content-Type: text/html

The Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date.

If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. If the browser is configured to store cookies, it will then keep this information until the expiry date. there is example of browser’s header:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.8 (X11; I; Linux 2.2.6-15apmac ppc)
Host: wbn.fook.com:1108
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[“name”].

Setting Cookies with PHP

PHP provided setcookie() function to set a cookie:

setcookie(name, value, expire, path, domain, security);

Where :

  • Name –  this sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS.
  • Value – the value of the named variable and is the content that you  want to store.
  • Expiry – This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
  • Path – This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
  • Domain – This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
  • Security – This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

 

Example of creating cookies:

<?("name", "Alechco Studio", time()+3600, "/","", 0);
   setcookie("age", "43", time()+3600, "/", "",  0);
?>
<html>   
   <head>
      <title>Setting Cookies with PHP</title>
   </head>  
   <body>
      <?php echo "Set Cookies"?>
   </body>   
</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables.

<html>   
   <head>
      <title>Accessing Cookies with PHP</title>
   </head>   
   <body>      
      <?php
         echo $_COOKIE["name"]. "<br />";         
         /* is equivalent to */
         echo $HTTP_COOKIE_VARS["name"]. "<br />";
         
         echo $_COOKIE["age"] . "<br />";         
         /* is equivalent to */
         echo $HTTP_COOKIE_VARS["name"] . "<br />";
      ?>      
   </body>
</html>

You can use isset() function to check if a cookie is set or not.

<html>  
   <head>
      <title>Accessing Cookies with PHP</title>
   </head>  
   <body>     
      <?php
         if( isset($_COOKIE["name"]))
            echo "Welcome " . $_COOKIE["name"] . "<br />";        
         else
            echo "Sorry... Not recognized" . "<br />";
      ?>     
   </body>
</html>

Deleting Cookie with PHP

To delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.

<?php 
     unset($_COOKIE["yourcookie"]); 
     /*Or*/ 
     setcookie("yourcookie","yourvalue",time()-1); 
     /*it expired so it's deleted*/  

     setcookie( "name", "", time()- 60, "/","", 0); 
     setcookie( "age", "", time()- 60, "/","", 0); 
?>

Updating Cookie

<?php
     setcookie("color","red");
     echo $_COOKIE["color"];
     /*color is red*/
     /* your codes and functions*/
     setcookie("color","blue");
     echo $_COOKIE["color"];
    /*new color is blue*/
?>

Leave a Reply

Your email address will not be published.

*