To create, access and destroy/delete cookies in PHP. Through this tutorial, i am going to show you how to set, get and delete cookies in PHP.
A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer. Once a cookie has been set, all page requests that follow return the cookie name and value.
How To Create, Access,and Destroy 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; is as follows:
<?php setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]); ?>
Example of set cookie in PHP; is as follows:
$first_name = 'Laratutorials.com'; setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day
Get Cookie PHP
To retrieve the get cookie in PHP; is as follows:
<?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] => laratutorials.com)
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
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", "Laratutorials.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
To set, retrieve and delete in cookies php; Through this tutorial, you have learn how to set, get and delete cookies in PHP. And as well as uses of PHP cookies.