Browser Cookies with PHP

PHP
Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace. PHP.net

Here is an example of a cookie that checks to see how many times a person has visited the site. Note that it expires in 30 days.


$cookie_name = "VPA";
$cookie_days = 30;
$cookie_time = time()+60*60*24*$cookie_days;
$cookie_path = '';
$cookie_domain = '';
$cookie_secure = false;
$cookie_httponly = true;

if( !isset($_COOKIE[$cookie_name]) ) {
    $cookie_value = 0;
} else {
  $cookie_value = $_COOKIE[$cookie_name] + 1;
}
setcookie($cookie_name,$cookie_value,$cookie_time,$cookie_path,$cookie_domain,$cookie_secure,$cookie_httponly);

In your code you can check for the value of the cookie like this:


echo "Cookie VPA is $_COOKIE[VPA]";

The value can be a number or text. Once a cookie is created, you can update the value in the body of your code.


setcookie("VPA","red",$cookie_time);
echo $_COOKIE["VPA"];

Not that I switched from a number to alpha in this example. The cookies don’t care what the value is or if the type changes. Note that you cannot get the cookie expiration time. And if you leave it off in your setcookie, it will be reset to Session.

To get rid of a cookie, set its value to null and time to something in the past—zero works.


setcookie($cookie_name,'',0);
e.g.
set cookie('VPA','',0);