PHP Cookies

Cookies are text files which allow programmers to store some information on the client computer, and they are kept of use tracking purpose.

Create a Cookie

Setcookie() function is used to set a cookie.

setcookie(name, value, expiration);
  • $name - a name of the cookie. Example: "username"
  • $value - a value of the cookie. Example: "Jhon"
  • $expire - time (in UNIX timestamp) when the cookie will expire. Example: time()+"3600". A cookie is set to expire after one hour.
<?php setcookie("username", "Jhon", time()+3600); ?>

Cookie username is set with value Vijay which is set to expire after one hour on the user's computer.

Retrieve a Cookie Value

PHP $ _COOKIE variable is used to retrieve a cookie value.

<?php echo $_COOKIE["username"]; ?> 

isset() function is used, to detect cookie is set or not.

if (isset($_COOKIE["username"]))
  echo "Welcome " . $_COOKIE["username"] . "!<br>";
  echo "Welcome guest!<br>";

You can do the following to view the full $ _COOKIE array.

<?php print_r($_COOKIE); ?>

Delete a Cookie

To delete cookies, you just need to set a cookie on past date.

The following PHP code will delete, username cookie.

<?php setcookie("username", "Jhon", time()-3600); ?>