PHP Cookies

A Cookie can be defined as a thing that is used to store a small amount of data (maximum around 4KB) within the user's browser itself. Later, whenever the user revisits an already visited page, all the data in the cookie is automatically sent to the server within the request.

A very common use of cookies in PHP is to store username and password on your computer so that you don't have to login again each time you visit a website. We can make a cookie to last for a fixed amount of time ranging between a few seconds to several years as per our desire. We can even set a cookie to expire once the browser application is closed.

Setting a Cookie

In the following example, setcookie() is used to store the number of pages user views in the his current browser session. Here the expires argument is zero hence the cookie will disappear when the user closes his browser. Further, the domain argument is an empty string meaning the browser will only send the cookie back to the exact web server that created it.

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Setting a Cookie Example

<?php 
setcookie("yourViews", 5, 0, "/", "", false, true );
?> 

Accessing a Cookie

Below example will display nothing in first run as $_COOKIE[ "yourViews" ] doesn't exist. But when the user reloads the page to run the script again, the code will display 1 ( true ) because the browser has sent the yourViews cookie back to the server once hence second time the result will be:

Syntax

echo isset( $_COOKIE[Cookie Name] );

Accessing a Cookie Example

<?php
setcookie( "yourViews", 5, 0, "/", "", false, true );
echo isset( $_COOKIE["yourViews"] );
?> 

This will produce following result

1

Removing a Cookie

In order to remove the cookie, we use setcookie once again, only set the expiration date to be sometime in the past (here 60 seconds). This is done when you 'logout' of a site

Removing a Cookie Example

<?php
$t=time()-60; //this makes the time 60 seconds ago
setcookie( "visitor", "", $t);
echo "Cookie named visitor is no longer there";
?> 

This will produce following result

Cookie named visitor is no longer there