Cookie in PHP with Examples

A cookie is a small piece of data that the server-side application stores on the client-side (i.e., on the user's web browser). Cookies are commonly used in web applications to store user-specific information such as login credentials, user preferences, or the contents of a shopping cart. On subsequent requests from the same client, the server can retrieve this information from the cookie.

How to set a cookie in PHP

The setcookie() function in PHP is used to set a cookie. The setcookie() function has the following basic syntax:

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

In the above general form of the "setCookie()" function, there are seven arguments, and following is a list and brief description of all seven arguments.

Consider the following PHP code that demonstrates how to set a cookie in PHP:

setcookie("username", "william", time()+3600, "/");

The above PHP code creates a cookie called "username" with the value "william" on the server's root path. The above "setcookie()" function takes four arguments, which are briefly described below:

How to retrieve a cookie in PHP

Use the PHP $_COOKIE superglobal array to retrieve the cookie. As an example:

$username = $_COOKIE["username"];

PHP Cookie Example

Here is an example illustrating how to create cookies in PHP.

<?php
    // Set the cookie name and value
    $cookieName = "fresherearth";
    $cookieValue = "Computer Programmer";

    // Set the expiration time for the cookie (30 days from now)
    $expirationTime = time() + (86400 * 30);     // 86400 seconds = 1 day

    // Set the cookie with the above name, value, and expiration time
    setcookie($cookieName, $cookieValue, $expirationTime);

    // Check if the cookie exists and print a message accordingly
    if (!isset($_COOKIE[$cookieName])) {
        echo "Cookie not found. A new cookie has been created.";
    } else {
        echo "Cookie exists with the name: " . $cookieName . " and value: " . $_COOKIE[$cookieName];
    }
?>

Here is the sample output of the above creating cookies example code in PHP. This is the screenshot of the sample output at the first run of the above PHP program in the web browser:

create cookie in php

Now, if you run the above creating cookie program in PHP for the first time, a cookie with the name "fresherearth" and value "Computer Programmer" is created for 30 days. Therefore, if you re-run the same program or refresh your browser for the same program, you will see the following output this time:

php create cookie

If you create the above cookie for only 2 seconds, then you will see that your cookie will be created and expire in only 2 seconds. After creating your cookie for 2 seconds, if you refresh your browser after 2 seconds, you will see the message "Creating cookie.." after 2 seconds of creating your cookie using the above program in PHP.

Here is an example showing how to retrieve cookies in PHP.

<?php
    $cookieName = "fresherearth";

    // Check if the cookie exists or not
    if (!isset($_COOKIE[$cookieName])) {
        // If the cookie doesn't exist, set it with a value and expiration time
        $cookieValue = "Computer Programmer";
        $expirationTime = time() + (86400 * 30);     // 86400 seconds = 1 day
        setcookie($cookieName, $cookieValue, $expirationTime);
    }

    // Retrieve the cookie value and print it along with the cookie name
    if (isset($_COOKIE[$cookieName])) {
        echo "Cookie is retrieving...<br>";
        echo "Cookie is retrieved successfully...<br><br>";
        echo "Name of the cookie = " . $cookieName . "<br>";
        echo "Value of the cookie = " . $_COOKIE[$cookieName] . "<br>";
    } else {
        echo "Error occurred...<br>";
        echo "Exiting...<br>";
    }
?>

Here is the sample output produced by the above retrieving cookie example code in PHP.

php retrieve cookie

In PHP, use the isset() function on the superglobal variable $_COOKIE to determine whether or not a cookie has been set. Let's take an example of checking whether a cookie is already set or not.

<html>
<head>
   <title>Checking cookie is set or not in PHP</title>
</head>
<body>
<?php
   if (isset($_COOKIE['cookieName'])) {
      echo "Cookie is set<br>";
      echo "You are ".$_COOKIE['cookieName'];
   } else {
      echo "Cookie is not set<br>";
      echo "You can't proceed!";
   }
?>
</body>
</html>

As the cookie is not set, here is the sample output produced by the above cookie example code in PHP.

php check cookie set

Now try another example to check for cookies, whether they are set or not, on the user's computer in PHP.

<html>
<head>
   <title>Checking cookie is set or not in PHP</title>
</head>
<body>
<?php
   $cookieName = "fresherearth";
   if (isset($_COOKIE[$cookieName])) {
      echo "Cookie is set<br>";
      echo "You are ".$_COOKIE[$cookieName];
   } else {
      echo "Cookie is not set<br>";
      echo "You can't proceed!";
   }
?>
</body>
</html>

As a result of the cookie named "fresherearth" being set by the example program for creating cookies, the output of the checking whether the cookie is set or not example code in PHP will be "true" this time.

php cookie

To delete any cookie in PHP, just create the cookie again with the same name but set the expiration time to 1 hour ago or earlier, that is, set time as time()-3600.

Here is an example showing how to delete cookies in PHP from the user's computer.

<html>
<head>
   <title>Delete Cookie Example in PHP</title>
</head>
<body>
<?php
   $cookieName = "fresherearth";
   setcookie($cookieName, "", time()-3600);
   echo "The cookie <b>$cookieName</b> is deleted successfully.";
?>
</body>
</html>

Here is an example of what the above PHP code for deleting a cookie produces.

php delete cookie

Here is an example showing how to check whether the cookie is deleted or not in PHP.

<html>
<head>
   <title>Check Cookie is deleted or not Example in PHP</title>
</head>
<body>
<?php
   $cookieName = "fresherearth";
   if(isset($_COOKIE[$cookieName])) {
      echo "The cookie <b>$cookieName</b> is not deleted.";
   } else {
      echo "The cookie <b>$cookieName</b> is deleted.";
   }
?>
</body>
</html>

Here is an example of what the above PHP example program does when it checks to see if the cookie has been deleted.

php cookie example

PHP Online Test


« Previous Tutorial Next Tutorial »