PHP Cookie Basics

This page provides a basic overview of using cookies with PHP. Topics covered include:

Setting a Cookie

To set a cookie, simple use the setcookie() method. The basic format is:

setcookie(cookieName, cookieValue, cookieDate);

This is fairly straight forward. However, a example is in order:

setcookie('MyCookieVal', 'This is the cookie data stored in the browser', time()+60*60*24*1);

This creates a cookie named MyCookieVal in a browser with a value of This is the cookie data stored in the browser. The cookie will expire in 1 day based on the value calculated with the time() function.

For the application I am working on, I need to create a cookie that stores multiple values in a single cookie. In addition, some of the parts of the cookie value needs to be encrypted using an MD5 hash. The hash stores an authentication value for site access. The example demonstrates this feature. The various parts of the cookie value are separated by commas. The MD5 value is created by combining one of the form fields along with a secret seed value. The technique is described in detail in the book linked at the end of the page.

Demo: cookie01.php - Source: cookie01.php

 

Reading a Cookie

Any cookies stored in the browser for your site are stored in the $_COOKIE array. The following example shows how the cookie is data is extracted and used. It also demonstrates how the MD5 values are compared.

Demo: cookieRead01.php - Source: cookieRead01.php

For more information on this subject, this book is a great resource: