How to Create, Read, Update and Delete a Cookies with PHP

By | September 10, 2014

As you know HTTP doesn’t remember anything as it is a stateless protocol. If we want to send information to another page than we have to use either session’s or cookies. In this below tutorial you get a quick look to Cookies and How we create, read, update and delete Cookies in PHP.

Create Cookies with PHP

For creating cookies we use setcookie(). It will create the cookie and it took some parameter’s like name, value, time etc. Below cookie example will work for only 1 hour as we are setting the 3600 sec from the time of execution.

$cookieName="demoCookie"; // giving a cookie name
$cookieValue="Vivek Moyal cookie demo"; // value to the cookie
$setcookie($cookieName,$cookieValue,time()+3600) // setting the cookie for 1 hour

 Read Cookies With PHP

After creating the cookies we will read them by using the $_COOKIE. After setting the cookies we can use them on our other pages.

echo $_COOKIE["demoCookie] // showing cookie value

It will echo the “Vivek Moyal cookie demo”.

update Cookies With PHP

You want to update the cookie value than just set it again. Use setcookie() and change the value for $cookieValue.

$cookieValue="Value Changed"; // New value for our cookie

Now use the setcookie() again.

$setcookie($cookieName,$cookieValue,time()+3600) // setting the cookie for 1 hour

Now if you echo the demoCookie than you will get “Value Changed”.


Delete Cookies With PHP

If you want to remove or delete a cookie than there is no any special method for it for doing this you need to set your cookie time in minus or can say in past.

$setcookie($cookieName,'',time()-3600) // setting the cookie for 1 hour back

Due to using “-” instead of “+” it will set the cookie life to – 1hr that is past so it will delete the cookie also use blank value.

Use Time for Cookie

1 Hour = time() + 3600;

1 Day = time()+60*60*12

Till Midnight = strtotime(‘today 23:59’)

30 Days = strtotime( ‘+30 days’ )

10 year = time() + (10 * 365 * 24 * 60 * 60)

Thank You for reading the tutorial How to Create, Read, Update and Delete a Cookies with PHP if you need any help or having any issue than please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *