Web Programming TutorialsLearn Working with Cookies in PHP

Learn Working with Cookies in PHP

Working-with-Cookies-in-PHP

Introduction to Cookie
Have you ever done something like this while shopping online? Have you picked a few products and added them to your shopping cart, but did not purchase them, left them in your cart and logged out from the website? Did you notice that the next time you logged in to that website using the same browser, the selected products were still in your shopping cart? However, if you log in to the same website, using the same username but a different browser, you found the shopping cart empty? Do you know the reason why this happened? This happened because of the stored information in the browser Cookie. Let’s understand how cookies works.

What is an HTTP Cookie?
HTTP Cookie is also known as a web cookie, an Internet cookie or a browser cookie. It is a text file present in the browser of the client machine or computer which stores a small piece of information sent from a website when browsed by the user. When a user loads that website again, the browser sends the stored cookie back to the server which notifies the user’s past activities. HTTP Cookies are primarily used to store the user’s browsing history, shopping cart information for an online store, login passwords and other such information.

PHP supports HTTP cookies and it involves following three steps for its operation.

  • Sever side script pushes a piece of information such as name, address, etc. to the client browser when a website is browsed.
  • Client side browser stores this information in the cookies, which are the text files on which the browser operates.
  • When a website is browsed again, then browser sends these cookies i.e. stored information back to the server which is used by the server to identify the user’s browsing history.

Below in this chapter, we are going to learn about the PHP Cookie syntax and basic HTTP Cookie operations with examples.

Cookie Syntax in PHP
A Cookie in PHP is created with the setcookie () function which has 7 parameters.

SYNTAX DESCRIPTION
setcookie (name, value, expire, path, domain, secure, httponly); It is an in-built function which has 7 parameters.
isset (); It is an in-built function which helps to find out if a cookie value is set (enabled) or not.
$_COOKIE [“userID”] It is a global variable that retrieves a named cookie value.

This is to be noted that the ‘name’ parameter is a required field and rest all other parameters are optional. Given below is the description of all parameters.

  • Name: It is the Cookie’s name which is stored in an environment variable _COOKIE. Also we can use this variable to access browser cookies.
  • Value: It is the actual content to be stored, which is assigned to the Cookie’s named variable
  • Expiry: This parameter specifies a time in future that is elapsed since 01st Jan 1970 00:00:00 GMT. When this time expires, the cookie becomes inaccessible. It is an important parameter when not set, it will expire the cookie automatically after the browser is closed.
  • Path: This parameter specifies that the cookie will be valid for this server side directory. When we specify a forward slash character (/) as its value then it will permit the cookie to be valid across all directories.
  • Domain: This parameter specifies the domain name. Both Domain and Path together define the scope of the cookie. They tell the browser the website to which cookie belongs. If we do not specify Path and domain then they will default to the domain and path of the resource that was requested.
  • Secure: The Secure parameter does not have any value and it is present with the attribute name as Secure to enable the behavior. It informs the browser to use cookies only via secured or encrypted connections. Also, we can set values as 0 or 1. Value set as 1 directs the browser that cookies should be used via secured or encrypted connections, whereas value set as 0 revokes this restriction from browser.
  • Httponly: The Httponly parameter does not have any value and it is present with the attribute name as HttpOnly to enable the behavior. It informs the browser that cookies should not be exposed to the channels other than HTTP (and HTTPS) requests. Therefore, it becomes inaccessible through non-HTTP methods such as JavaScript calls (document.cookie), etc. Thus provides security to the information stored in cookie.

Example: The HTTP request that was sent to a webpage will look as shown below.

It is sent to the xyz.com domain which has access to /tutorials directory. It accepts secured connection via HTTP (and HTTPS) only. It will expire on Wed, 18 May 2020 11:34:01 GMT.

HTTP/1.0 200 OK

Set-Cookie: NAME=PHP; Expires=Wed, 18 May 2020 11:34:01 GMT; Path=/tutorials; Domain=xyz.com; Secure; HttpOnly

Cookies Operations
We are going to do the following operations using PHP Cookies with examples.

  • Create and retrieve a value from Cookie with PHP: As discussed before, we can set cookies using the setcookie () function of the PHP after entering required parameters as shown below. It will create two cookies named as “userID” with the value “Appy” and “address” with the value “Toronto, ON”. The cookie will expire after 2 hours (3600 * 2 = 7200 seconds). The forward slash “/” indicates that the cookie is available in the entire website directory.

Cookies values can be retrieved using the global variable $_COOKIE [“userID”] as shown below. In the below example, we have used isset () function. As discussed before, this function returns a Boolean value to find out if the cookie is set or not. If set, this function will return true, otherwise false.

<?php
$cookie_name = "userID"; $cookie_name_value = "Appy";
$cookie_address = "address"; $cookie_address_value = "Toronto, ON";
setcookie($cookie_name, $cookie_name_value, time()+7200, "/","", 0);
setcookie($cookie_address, $cookie_address_value, time()+7200, "/", "",  0);
echo "Two Cookies values are set successfully! <br><br>";
?>
<html>
   <head>
      <title>Cookies - Create &amp; Retrieve</title>
   </head>
   <body>
    <?php
    echo "Retrieving Cookies values! <br><br>";
    if(isset($_COOKIE["$cookie_name"])) {
                echo "cookie_name: '" . $_COOKIE[$cookie_name] . "' is created!<br><br>";
                echo "cookie_address '" . $_COOKIE[$cookie_address] . "'is created!<br><br>";
    } else {
                echo "cookie_name: '" . $cookie_name . "' is not set!<br><br>";
    }
      ?>
   </body>
</html>

Output: When we run above PHP code on web server, it will display below output.

  • Modify Cookie value with PHP: We can modify an existing cookie after setting a new value to the named cookie using the setcookie () function again as shown below. Here, the named cookie “userID” value has changed to “Abhi” and cookie “address” value has changed to “New Delhi, INDIA”.
<?php
$cookie_name = "userID"; $cookie_name_value = "Abhi";
$cookie_address = "address"; $cookie_address_value = "New Delhi, INDIA";
setcookie($cookie_name, $cookie_name_value, time()+7200, "/","", 0);
setcookie($cookie_address, $cookie_address_value, time()+7200, "/", "",  0);
echo "Two Cookies values are modified successfully! <br><br>";
?>
<html>
   <head>
      <title>Cookies - Modify</title>
   </head>
   <body>
    <?php
    echo "Retrieving Cookies values! <br><br>";
    if(isset($_COOKIE["$cookie_name"])) {
                echo "cookie_name: '" . $_COOKIE[$cookie_name] . "' is modified!<br><br>";
                echo "cookie_address '" . $_COOKIE[$cookie_address] . "'is modified!<br><br>";
    } else {
                echo "cookie_name: '" . $cookie_name . "' is not set!<br><br>";
    }
      ?>
   </body>
</html>

Output: When we run above PHP code on web server, it will display below output.

  • Deletion of Cookie with PHP: We can delete an existing cookie after setting a new value as “” to the named cookie using the setcookie () function again as shown below. Here, the named cookie “userID” value has changed to “” and cookie “address” value has changed to “”. However this approach does not work always, therefore it is recommended to set the cookie with a date in the setcookie () function that has already expired (here expire parameter is set to time ()-7200 i.e. two days before).
<?php
$cookie_name = "userID"; $cookie_name_value = "";
$cookie_address = "address"; $cookie_address_value = "";
setcookie($cookie_name, $cookie_name_value, time()-7200, "/","", 0);
setcookie($cookie_address, $cookie_address_value, time()-7200, "/", "",  0);
echo "Two Cookies values are deleted successfully! <br><br>";
?>
<html>
   <head>
      <title>Cookies - Deletion</title>
   </head>
   <body>
    <?php
    echo "Retrieving Cookies values! <br><br>";
    if(isset($_COOKIE["$cookie_name"])) {
                echo "cookie_name: '" . $_COOKIE[$cookie_name] . "' is deleted!<br><br>";
                echo "cookie_address '" . $_COOKIE[$cookie_address] . "'is deleted!<br><br>";
    } else {
                echo "cookie_name: '" . $cookie_name . "' is not set!<br><br>";
    }
      ?>
   </body>
</html>

Output: When we run above PHP code on web server, it will display below output.

Conclusion
In this chapter, we have learnt about the PHP Cookie function, its syntax and various operations such as Cookie creation, retrieval of values from Cookie, modification of those values and deletion of Cookie. In the case of Cookies, since information is stored at the client side therefore, they are more prone to security attacks and often they generate inconsistencies between the client state and the information stored in the Cookies. To overcome such inconsistencies, the information can also be stored at the server side using a PHP session which we are going to learn in the next chapter.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -