The main difference between a cookie and a session is that a cookie is stored on your computer, and a session is not. Although cookies have been around for many years and most people do have them enabled, there are some who do not. Cookies can also be removed by the user at any time, so don’t use them to store anything too important.
How to Set or create a Cookie
The setcookie() function is used for setting Cookie
$user_name = 'Arjun'; setcookie('user_name',$user_name,time()+3600); /* expire in 1 hour */
Above we set the user name equal to ‘Arjun’, actually username will come from the database in real time for the sake of this tutorial i am using. and the cookie will expire in 1Hour.
PHP cookies can be set with more specific directives, including path, domain, secure, and httponly.
setcookie('user_name',$user_name,time() + 3600,'/','arjun.net.in',true,true);
How to Get or Retrieve a Cookie
The PHP $_COOKIE variable is used to retrieve a cookie value.
echo 'Hello '.($_COOKIE['user_name']!='' ? $_COOKIE['user_name'] : 'Guest'); // output Hello Arjun
In the above code, we retrieve the value of the user_name if cookie is set, and display it to the page
How to Delete a Cookie
To delete Cookie , just set the expiration date in past, bellow example expiration date set to 1Hour ago
// // set the expiration date to one hour ago setcookie('user_name','',time()-3600); /* expire in 1 hour past */
REMEMBER:Cookies need to be set in the header. This means they must be sent before any HTML is set to the page, or they will not work.