Signup/Sign In

PHP Cookies

Cookie is a small piece of information stored as a file in the user's browser by the web server. Once created, cookie is sent to the web server as header information with every HTTP request.

You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.

Before we move on to how to create, update and delete a cookies, let's learn a few realworld use of cookies.


Realworld Use of Cookies

  1. To store user information like when he/she visited, what pages were visited on the website etc, so that next time the user visits your website you can provide a better user experience.
  2. To store basic website specific information to know this is not the first visit of user.
  3. You can use cookies to store number of visits or view counter.

I hope this gives you an idea about how you can utilize cookies in your web application.


Types of Cookies

There are two types of cookies, they are:

  1. Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the browser is closed.
  2. Persistent Cookie: To make a cookie persistent we must provide it with an expiration time. Then the cookie will only expire after the given expiration time, until then it will be a valid cookie.

Creating a Cookie in PHP

In PHP we can create/set a cookie using the setcookie() function.

Below we have the syntax for the function,

setcookie(name, value, expire, path, domain, secure)

The first argument which defines the name of the cookie is mandatory, rest all are optional arguments. Let's understand what are the available arguments that we can supply to the setcookie() function to set a cookie.

ArgumentWhat is it for?
nameUsed to specify the name of the cookie. It is a mandatory argument. Name of the cookie must be a string.
valueUsed to store any value in the cookie. It is generally saved as a pair with name. For example, name is userid and value is 7007, the userid for any user.
expireUsed to set the expiration time for a cookie. if you do not provide any value, the cookie will be treated as a session cookie and will expire when the browser is closed.
pathUsed to set a web URL in the cookie. If set, the cookie will be accessible only from that URL. To make a cookie accessible through a domain, set '/' as cookie path.
domainThe domain of your web application. It can be used to limit access of cookie for sub-domains. For example, if you set the domain value as wwww.studytonight.com, then the cookie will be inaccessible from blog.studytonight.com
secureIf you set this to 1, then the cookie will be available and sent only over HTTPS connection.

So if we want to create a cookie to store the name of the user who visited your website, and set an expiration time of a week, then we can do it like this,

<?php

setcookie("username", "iamabhishek", time()+60*60*24*7);

?>

To access a stored cookie we use the $_COOKIE global variable, and can use the isset() methos to check whether the cookie is set or not.

Let's have a complete example where we will set a cookie and then retrieve it to show its value in the HTML page.

<?php
// set the cookie
setcookie("username", "iamabhishek", time()+60*60*24*7);
?>
<html>
    <body>
    
    <?php
    // check if the cookie exists
    if(isset($_COOKIE["username"]))
    {
        echo "Cookie set with value: ".$_COOKIE["username"];
    }
    else
    {
        echo "cookie not set!";
    }
    ?>
    
    </body>
</html>

So by providing the name of the cookie inside the square brakets with the global variable $_COOKIE[] we can access the cookie.

NOTE: setcookie() function should be placed before the starting HTML tag(<html>).


Updating Cookie in PHP

To update/modify a cookie, simply set it again. For example, if we want to update the username stored in the cookie created above, we can do it using setcookie() method again,

<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time()+60*60*24*7);
?>
<html>
    <body>
    
    <?php
    // check if the cookie exists
    if(isset($_COOKIE["username"]))
    {
        echo "Cookie set with value: ".$_COOKIE["username"];
    }
    else
    {
        echo "cookie not set!";
    }
    ?>
    
    </body>
</html>

We just update the value of username cookie from iamabhishek to iamNOTabhishek.


Delete a Cookie in PHP

To delete/remove a cookie, we need to expire the cookie, which can be done by updating the cookie using the setcookie() function with expiration date in past.

<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time() - 3600);
?>
<html>
    <body>
    
    <?php
    
    echo "cookie username is deleted!";

    ?>
    
    </body>
</html>

And with this, we now know how to create a cookie, how to update it and how to delete it when we no longer need it. Next up, Sessions!