PHP Cookies

  • Cookie is a very small file which is used to identify a user. Cookie lets you know if a new user has visited your web page or it was someone who has visited your page before. Server embeds the cookie with the computer of the user who visits the page. Now every time when the same user visits the page, the cookie that has been embedded with his system is retrieved.

Creating a Cookie

setCookie() function is used to create a cookie.

setCookie(name,value,expiry,path,domain,secure,httponly);

The function has following parameters-

  • name= (Required) It is the name of the cookie.
  • value= (Required) It is the initialization value of the cookie.
  • expiry= (Required) It is the time at which the cookie will be expired automatically.

It can be set by adding the required duration in the current time. Current time can be obtained using time() function.

  • path= (Optional) It specifies the path in the website on which the cookie will be available. To make it available on entire domain, use "/"
  • domain= (Optional) It specifies the domains and the subdomains in which the cookie will be available.
  • secure= (Optional) It will have two values, either true or false. If it is set to true, the cookie will be set only if a secure connection exists.
  • httponly= (Optional) It will have two values, either true or false. If it is set to true, the cookie will be accessible only through HTTP protocol.

Above program sets a cookie with the name UserName, value Peter and it will expire after 1 hour from the time it is set.

Retrieving a cookie

  • A cookie can be retrieved using $_COOKIE['cookieName'].
<!Doctype html>

<body>

<?php

if(isset($_COOKIE['UserName']))

{

echo "The username is ".$_COOKIE['UserName'];

}

else

{

setcookie("UserName","Peter",time()+60*60);

}

?>

</body>

</html>

Output

cookie

Deleting a Cookie

To delete a cookie, set its time in past.

setCookie("UserName", "Peter", time()-1);