The following code shows an Example of Creating Cookies in PHP.

Cookies offer a convenient way to store a small amount of client information. The following example works as follows. At first, the user enters some values in the text fields in the HTML form. When the user clicks on the Submit button, the if block in the PHP script executes. It calls the setcookie() method to create a cookie with name My_Choices.

Further note that you may need to refresh the web page so that the cookie gets created.

<?php
 if(isset($_POST['submit']))
 {
	$sport=$_POST['t1'];
	$book=$_POST['t2'];
        $place=$_POST['t3'];
        $expiry=time()+12*24*60*60;
        $choices=(object)array("Sport"=>$sport, "Book"=>$book, "Place"=>$place);
        $cookie_name="My_Choices";
	$cookie_info=(object)array("values"=>$choices, "expiry_date"=>$expiry);
	setcookie($cookie_name, json_encode($cookie_info), $expiry);
}
        echo $_COOKIE['My_Choices'];
 $mycookies=json_decode($_COOKIE['My_Choices']);
 $info=$mycookies->values;
 $s=$mycookies->values->Sport;
 $b=$mycookies->values->Book;
 $p=$mycookies->values->Place;
 $expiry_date=date("Y-m-d H:i:s", $mycookies->expiry_date);

 echo "<br>Favourite Sport: ",$s,'<br>';
 echo "Favourite Book: ",$b,'<br>';
 echo "Favourite Place: ",$p,'<br>';
 echo "Expiry Date: ",$expiry_date,'<br>';
 
?>
<html>
 <head>
   <title>Creating Cookies</title>
 </head>
 <body>
   <div style="margin:50px;">
     <h1>Enter Your Choices</h1>
     <form name="myform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
	Your Favourite Sport: <input type="text" name="t1"><br/><br/>
        Your Favourite Book: <input type="text" name="t2"><br/><br/>
        Your favourite Place: <input type="text" name="t3"><br/><br/>
	<input type="submit" name="submit" value="Submit"><br/>
     </form>
   </div>
 </body>
</html>

Output

Example of Creating Cookies in PHP - Cookie Data and Expiry Date
Example of Creating Cookies in PHP – Cookie Data and Expiry Date

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP