This PHP tutorial describes how to use cookies in PHP. It explains how to set cookies in a user's machine and retrieve it for later use.

PHP Create a Cookie

The following example creates a cookie named "Username" set with the value "Alex". This cookie is set to be used for 15 days:

Example:

<?php
$cookie_name = "Username";
$cookie_value = "Alex";
setcookie($cookie_name, $cookie_value, time() + (86400 * 15), "/"); //Set for 15 days (86400 = 1 day)
?>

As in the example above, a cookie has been set using the setcookie() function that can be retrieved later. The following code retrieves this cookie along with its value.

PHP Retrieve a Cookie

Example:

<?php
if(!isset($_COOKIE[$cookie_name])) {
  echo "$cookie_name cookie not set!";
} else {
  echo "The '".$cookie_name."' cookie is set with the value '".$_COOKIE[$cookie_name]."'.";
}
?>
Output:
The 'Username' cookie is set with the value 'Alex'.
  • The most recently set cookie can be retrieved after refreshing on the same page.
  • To modify the cookie, use the setcookie() function again.
  • Also, for deleting the cookie use the setcookie() function and set the cookie in the past.