How to Create, Read, Update and Delete a Cookie in PHP

In this tutorial, I will explain how to create, read, update and delete the cookie in PHP.

What is a cookie ?
Generally, the cookie will be stored in client side i.e in a browser, Each time the same computer requests a page with a browser, it will send the cookie to the server. This mechanism is mostly used in the shopping carts.

How to create the cookie
By using the setcookie method to create the cookie in PHP. Here we have to pass some values in this method, those are name, value, expire, path.
<?php
$cookie_name = 'site_user';
$cookie_value = 'TechiesBadi';
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
?>
This cookie will expire after 30 days. Using "/", the cookie is available in all website (otherwise, select the directory you prefer).
If you want to change the expire days just change as 30 to your own days.

How to read the cookie
By using global variable $_COOKIE to retrieve the stored cookies in PHP.
<?php
$cookie_name = 'site_user';
if(!isset($_COOKIE[$cookie_name])) {
  print 'Cookie ' . $cookie_name . ' does not exist...';
} else {
  print  $cookie_name . 'value is: ' . $_COOKIE[$cookie_name];
}
?>
How to update the cookie
Actually, there is no method for updating the cookie just simply recreate the cookie by using setcookie method.
<?php
$cookie_name = 'site_user';
$cookie_value = 'Techies';
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
?>
How to delete the cookie
By using the setcookie() function with an expiration date in the past.
<?php
$cookie_name = 'site_user';
unset($_COOKIE[$cookie_name]);
// empty value and expiration one hour before
$res = setcookie($cookie_name, '', time() - 3600);
?>

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff


EmoticonEmoticon