News & UpdatesProgrammingWeb programming StoreMy Projects

PHP Tutorial – 15 – Cookies

A cookie is a small file kept on the client’s computer that can be used to store data relating to that user.

Creating cookies

To create a cookie the setcookie function is used. This function must be called before any output is sent to the browser. It has three mandatory parameters that contain the name, value and expiration date of the cookie.

setcookie("lastvisit", date("H:i:s"), time() + 60*60);

The value is here set with the date function, which returns a string formatted according to the specified format string. The expiration date is measured in seconds and is usually set relative to the current time in seconds retrieved through the time function. In this example, the cookie expires after one hour.

Once the cookie has been set for a user this cookie will be sent along the next time that user views the page and can then be accessed through the $_COOKIE array.

if (isset($_COOKIE['lastvisit']))
  echo "Last visit: " . $_COOKIE['lastvisit'];

Deleting cookies

A cookie can be deleted manually by recreating that same cookie with an old expiration date. It will then be removed when the browser is closed.

setcookie("lastvisit", 0, 0);
Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours