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

An Example to Create and Display Cookies in PHP
An Example to Create and Display Cookies in PHP

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

Basic Programs in PHP