Codingtree

More often that not, we need to use information provided by a user in pages beyond the current page. Asking the user for the same information repetitively as user navigates from one page to another would would degrade the user-experience. For such cases, HTML uses cookies to hold small chunks of user-specific information using a key/value format. HTML stores these cookies at the client's machine, either in the memory or in the hard-disk.

In terms of requirement, user information can be either long-term (like storing user's information when creating a profile) or temporary (like items added in a shopping cart). Long-term information can be easily stored in a database or a file. But, storing temporary information in a database or a file may not be an efficient solution and using cookies is often a simpler solution.

PHP provides setcookie() function to enable PHP programs to set an HTML cookie. Here is the signature of the setcookie() function:

 bool setcookie($name, $value, $expirationtime, $path, $domain, $issecure, $isforhttponly); 

 Description of Arguments:
     $name: Name of the cookie.
     $value: (optional) Value of the cookie; default is NULL.
     $expirationtime: (optional) Time (in seconds) when the cookie will expire; default is 0.
     $path: (optional) The cookie will be available for all pages that are in this path and 
       including the path. Default is the current directory of the page that calls setcookie().
     $domain: (optional) Domain for which the cookie will be available.
     $issecure: (optional) For https connections, we need to set it to 1. Default is 0.
     $isforhttponly: (optional) If set to 1, then it would be available only via HTTP and not 
 	via other languages like Javascript. Default is 0.

Let us further understand cookies using a simple example (provided below). Please note that we must enable cookies in the browser for cookies to work (which includes this example as well!). This example provides a simple login page; we call it "cookie_form_login.html".

 <!doctype html>
 <html>
 <head> <h3>A Trivial Login Form </h3></head> 
 <body>
 <form name="input_form" method="POST" action="cookie_login.php"><br>

 Username: <input type="text" name="textUsername"><br>
 Password: <input type="password" name="passwordPassword"><br>
 <input type="submit" name="submitButton" value="Login"><br><br><br>
 Feedback/Comments:<br>
 <textarea name="textareaComments"> We appreciate your comments.  </textarea>

 </form> 
 </body></html>

When the user fills the information and submits the form, the browser takes the user to the server-side action page: "cookie_login.php". This page (provided below) invokes setcookie() to create a cookie named "username". Since HTML sends cookies as part of HTTP's header, we must call setcookie() before the <html> tag and also, before printing any value on the HTML page.

To elaborate, this action page first creates a cookie, embeds it as part of the HTTP header, and then adds other information as part of HTTP data; after this, the HTTP server sends the page back to the client browser.

 <?php
 if (isset($_POST["textUsername"])) {
     setcookie("username", $_POST["textUsername"], time()+3600);
 }
 ?>

 <!doctype html>
 <html>
 <?php
 if ($_POST) {
     $username = $_POST["textUsername"];
     echo "Welcome, $username to this trivial page!!<br>";
     echo "<br><a href=cookie_view.php> View your profile </a>";
 } else { 
     /* Let us see if cookie is set for username */
     var_dump($_COOKIE);
     if (isset($_COOKIE["username"])) {
         $username = $_COOKIE["username"];
         echo "<br>Welcome, $username to this trivial page!!<br>";
         echo "<br><a href=cookie_view.php> View your profile </a>";
     } else {
         echo "<br>You most certainly need to login!! <br>";

     }
 }
 ?>
 </html>

The "cookie_login.php" page first verifies if the $_POST["textUsername"] field is set. If it is set, then this means that the user has reached this page after filling information from the "cookie_form_login.html" page and so we use setcookie() to create a "username" cookie. We also provide "time()+3600" as expiration time for this cookie, which means that the cookie would expire in 3600 seconds (or 1 hour) from now. For the sake of simplicity, we do not include the remaining (optional) arguments of setcookie() function.

Next, "cookie_login.php" again checks if the $_POST array is set; if it is set, then it extracts the $username from the $_POST array. Else, it checks if the cookie is set for the username and if so, then it extracts the $username from the $_COOKIE array; $_COOKIE is an alias for $HTTP_COOKIE_VARS array. The array $_POST can be NULL if the user reloads this page without being redirected from the "form_login.html" page and in that case, the logical thing would be to load the $username from a stored cookie, if one exists!

Here is the output of cookie_login.php page, if we login as "user1001" on the form_login.html page:



Figure: Action Method: PHP Login page (using Cookies)

To demonstrate continuity of HTML cookies, "cookie_login.php" page also contains a link, "View your profile", to another page, "cookie_view.php", where the user can view profile information. Thus, overall the HTML flow includes three different files and their flow is shown below:

           HTML Form                         Form Action File                Page Link
      ------------------------            -------------------- 	          ------------------ 
     |"cookie_form_login.html"|  ----->  | "cookie_login.php" |  ----->  | "cookie_view.php"|
      ------------------------            -------------------- 	          ------------------ 
 			     Submit the Form.			Click the  
 			    Form data is passed 	    "View your profile"
 			     as $_POST array.

 	Figure: HTML Flow when submitting a Form and viewing user-data using HTML Cookies.

If the user were to click the "View your profile" link, then "cookie_login.php" page would redirect the user to "cookie_view.php" page (provided below). This page simply checks if the cookie is set for "username" and if it is set, then it prints a message for the user. If the cookie is not set, then it prints that it could not find the profile. Thus, this example demonstrates that cookies can be used as a means of transferring temporary information from one page to another.

 <!doctype html>
 <html>
 <?php
 echo "Let us print _COOKIE <br>";
 var_dump($_COOKIE);
 if (isset($_COOKIE['username'])) {
     $username = $_COOKIE['username'];
     echo "<br>$username, here is the profile! <br>";
     echo "Name: $username<br>";
 } else {
     echo "No profile found! <br>";
 }
 ?>
 </html>

If we were to click "View your profile" link, then the browser would display the following text:

 Let us print _COOKIE
 array(1) { ["username"]=> string(8) "user1001" }
 user1001, here is the profile!
 Name: user1001

Now, if we were to clear the cache in the browser and then reload the page ("cookie_view.php"), then the page would find that the cookie is not set. Here is the text displayed by the browser:

 Let us print _COOKIE
 array(0) { } No profile found! 

However, in spite of their great value-add, HTML cookies suffer from one major drawback! Sometimes browsers disable cookies and in that case, we can not store temporary user-information on the client box. In such cases, it is important to have another mechanism (like PHP sessions) that can store user-specific mechanism.





comments powered by Disqus