Cookies in PHP

To create a cookies use the PHP setcookie function.

setcookie ($name, $value, time() + 86400);

This function has many arguments and only a subset are shown here (for a full list read the PHP manual). The first argument is the name of the cookie, then the value assigned to that cookie and finally the time for which the cookie will be active.

NB: Cookies must be set before the headers of the page are sent, i.e. cookies must be the first thing set in a document (must come before the HTML tag).
if($_COOKIE[$name] == $value)
   echo 'Cookies enabled';

To access the value of a cookie you can use the $_COOKIE global array. This maps the name of each cookie to its value.

setcookie ($name, '', time() - 86400);

To delete a cookie you need to set the time to a date in the past to invalidate the cookie.




No tags