PHP has some built-in functions that are used to create, modify, and delete cookies. In this tutorial, we will show you how to set, get, and delete cookies in PHP with examples.
How to Create, Access and Delete Cookies in PHP?
Here are functions to set, get, and delete cookies:
#1 Set Cookie
In php, You can use the setcookie() function to set a cookie.
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 = 'Tutsmake.com'; setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day
#2 Access Cookie
To retrieve or access a cookie in PHP, you can use $_COOKIE
variable.
Here is an example to get a cookie:
<?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] => Tutsmake.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');
#3 Delete Cookie
In PHP, you can use setcookie() function with expiration time to remove already set cookies
Here is an example to destroy a cookie:
<?php setcookie("first_name", "Tutsmake.com", time() - 360,'/'); ?>
#4 Modify a Cookie
To modify a cookie with a name, value, and expiration time, you can also use $_COOKIE
with isset()
.
Here is example to modify a cookie:
if(isset($_COOKIE["user"])) {
setcookie("user", "Jane Doe", time() + 3600, "/");
}
?>
Conclusion
In this tutorial, you have learn how to set, get and delete cookies in PHP.