PHP provided a setcookie () function to set a cookie. This task requires up to six arguments and should be called before the <html> tag. In each cookie this function should be called separately.

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

Here is the detail of all the arguments −

  • Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
  • Value − This sets the value of the named variable and is the content that you actually 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.

Following the example will create two cookies name and age of these cookies which will expire after one hour.

#example.php

<?php
   setcookie("name", "John Watkin", time()+3600, "/","", 0);
   setcookie("age", "36", time()+3600, "/", "",  0);
?>

Accessing Cookies with PHP

PHP provides many ways to access cookies. An easy way to use either the $ _COOKIE or $HTTP_COOKIE_VARS variable. Following the example will access all the cookies set in the example above.

#example.php

 <?php
         echo $_COOKIE["name"]. "";
         
         /* is equivalent to */
         echo $HTTP_COOKIE_VARS["name"]. "";
         
         echo $_COOKIE["age"] . "";
         
         /* is equivalent to */
         echo $HTTP_COOKIE_VARS["age"] . ""; 
?>

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

 <?php
         if( isset($_COOKIE["name"]))
            echo "Welcome " . $_COOKIE["name"] . "";
         
         else
            echo "Sorry... Not recognized" . "";
  ?>

 Deleting Cookie with PHP

Officially, to clear a cookie you must call setcookie () only with a name dispute but this does not always work well, however, and should not be relied upon.

Very safe to set cookie with expired date -

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