cookies in php

Cookies are stored by browser on user's computer. Cookies store small information.The information are sent to the server by the browser with each request.

In cookies different types of infomation can be stored like user-id,last visit date etc. In php, cookies are created by setcookie() method OR with $_COOKIE array.



<?php 

setcookie("cookie_name","value","time","path","domain","secure");

?>
ParameterDescription
cookie_nameName of the cookie is required.
valueInformation which we want to store in cookie.
time Life time of cookies in seconds. This is optional, if value is not set, by default cookie expires in 30 days.
path This is the path where cookie is availed. If "/" is set, the cookie will be availed to all scripts through out entire domain.
domainThis is optional. Here sub domain is metioned where cookie is availed. Use ".yourdomain.com", If want on all subdomains
secureThis is optional.If we want to use cookies only with https (secure mode) set this option true, by default it is false.

For example if we want to record page preview by a visitor in a month, we will do something like given below:

<?php

$count=1;

if(isset($_COOKIE["count"])){

$count=$_COOKIE["count"]+1; $time=time()+(60 * 60 * 24 * 30)); setcookie("count",$count,$time);

} ?>
Cookies are deleted by browser after expiry time. But we can delete cookies if we set past time as expiry of cookie.
<?php
 $time=time()-60;
 setcookie("count",$count,$time);  

} ?>

While using cookies, keep following limitations of cookies in mind.

1. If cookies are disabled in user's browser. You can't use.
2. Cookies store small data approx 4 KB
3. User can delete cookies any time.