How to Create, Access and Delete Cookies in PHP

How To Create,Access,and Destroy Cookies in PHP - Lara Tutorials

A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user’s computer. They are typically used to keeping track of information such as username that the site can retrieve to personalize the page when user visit the website next time.

Note:Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request.

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 *