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.

Syntax:
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.
Example:
<?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.

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

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

Example:
<?php
if (isset($_COOKIE["username"]))
  echo "Welcome " . $_COOKIE["username"] . "!<br>";
else
  echo "Welcome guest!<br>";
?>

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

Example:
<pre>
<?php print_r($_COOKIE); ?>
</pre>

Delete a Cookie

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

The following PHP code will delete, username cookie.

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