How to Create, Access and Delete Cookies in PHP

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.

Recommended PHP Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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