The following code examples demonstrate how to Create and Display Cookies in PHP.
How to Create and Display Cookies in PHP
In order to create a cookie in PHP, use the setcookie() method. Although the first parameter, cookie name is the only required parameter, you can also specify the cookie value and expiry date. Further, you can use the superglobal variable $_COOKIE[‘cookiename’] to retrieve the cookie.
<?php
$cookie_name="mycookie";
$value="A small piece of information";
$expirydate=time()+24*60*60;
setcookie($cookie_name, $value, $expirydate);
echo $_COOKIE['mycookie'];
?>
Output

Example to Delete a Cookie
The following example shows how to delete an existing cookie. Here, we call the setcookie() method again and provide the same cookiename as the name of the cookie we wish to delete. However, the expiry date of the cookie must be some date in the past.
<?php
$cookie_name="mycookie";
$value="A small piece of information";
$expirydate=time()+24*60*60;
setcookie($cookie_name, $value, $expirydate);
echo $_COOKIE['mycookie'];
// Deleting the cookie
$expirydate=time()-24*60*60;
setcookie($cookie_name, $value, $expirydate);
echo '<br>',$_COOKIE['mycookie'];
?>
Further Reading
Examples of Array Functions in PHP
- Android
- Angular
- ASP.NET
- AWS
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Data Science
- Data Structures and Algorithms
- Deep Learning
- Django
- Dot Net Framework
- Drones
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Scratch 3.0
- Smart City
- Software
- Solidity
- SQL
- TypeScript
- VB.NET
- Web Designing
- XML