Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

How to Set, Get and Delete Cookies in PHP?

This tutorial teaches you how you can set cookies, retrieve them and delete them using PHP. Cookies allow the webmaster to store information about the site visitor on their computer to be accessed again the next time they visit. One common use of cookies is to store your username and password on your computer so you don’t need to login again each time you visit a website. Cookies can also store other things such as your name, last visit, shopping cart contents, etc.

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);

This cookie is the same as above,but It is for use only on an SSL connection and it may not be used by JavaScript.

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.

Leave a Reply