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
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML