How to Create, Access and Delete Cookies in PHP

Cookies are small text files that are created by the server and stored on the user computer in around 4KB files. Cookies are

used to store some information when user visit the website we set the cookies and next time when the user comes to the

website we can retrieve the value of the cookie and manipulate the information or data for that particular user as per

requirement, so cookies are very helpful in the website and we can use it in multiple scenarios. in this tutorial, we will let

you know How to use cookies in PHP and How to Set Cookies, Get Cookies, Delete Cookies with PHP.

How to Create, Access and Delete Cookies in PHP

Use the following methods to set, get and delete cookies in PHP:

  • Set Cookie PHP
  • Get Cookie PHP
  • Delete Cookie PHP
  • Uses of PHP cookie

Set Cookie PHP

Let’s see the basic syntax of used to set a cookie in php:

<?php
 
setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);
 ?>

Example of set cookie in PHP:

$first_name = 'CodeOne.com';
setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day

Get Cookie PHP

To retrieve the get cookie in PHP:

<?php
     print_r($_COOKIE);    //output the contents of the cookie array variable 
?>

Output of the above code will be:

Output:

Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [first_name] => CodeOne.com)

If you want to get only single cookie in PHP. So, you can use the key while getting the cookie in php as follow:

echo 'Hello '.($_COOKIE['first_name']!='' ? $_COOKIE['first_name'] : 'Guest'); 

Delete Cookie PHP

If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that has already passed.

<?php
 
 setcookie("first_name", "CodeOne.com", time() - 360,'/');
 
?>

Uses of PHP cookie

  • The cookie is a file websites store in their users’ computers.
  • Cookies allow web applications to identify their users and track their activity.
  • To set cookies, PHP setcookie() is used.
  • To see whether cookies are set, use PHP isset() function.

Conclusion

How to cookie set, retrieve and delete in php. In this tutorial, you have learn how to set, get and delete cookies in PHP. And as well as uses of PHP cookies.

Leave a Reply

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