News & UpdatesProgrammingWeb programmingPartnersStore
Book Cover
Buy Now
Projects
Links

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 can take up to seven parameters, but only the first three are mandatory and contain the name, value, and expiration date of the cookie.

setcookie("lastVisit", date("G:i:s"), time() + 3600);

It’s necessary that this function is called before any output is sent to the browser.

Once the cookie has been set for a user this cookie will be sent along the next time that user views that 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.

setcookie("lastVisit", 0, 0);

If you like this tutorial please +1 it:


Leave a Reply