The following code example shows A Cookie in PHP to Store User Data.
Sometimes, we need to store more than just a simple string in a cookie. For instance, now our data may contain several fields such as user name, address, age, and so on. Moreover, suppose we also need to retrieve the different field values separately. In such a case, we can combine different fields of user data in an array and insert that array as the data in the cookie.
The following code shows how to create a cookie with several fields of user data. At first, we create three variables in this example that contain user name, place, and age. After that, we create an associative array by providing the key names and values using the above created variables. Then, we create an object from that array by typecasting. Also, we create a variable that stores the expiry date of 365 days. Further, we create another array that contains two values. The first one is the array that we have created previously. That array contains only the user data. However, the second element of this array stores the expiry date.
Because we need to retrieve the expiry date also, so we store it as a field in the data. After that, we call the setcookie() method with cookie name, data, and the expiry date. But for storing data, we need to use the json_encode() method that converts PHP array into JSON representation. When we need to retrieve these values we need to use the json_decode() method.
<?php
$name="Asavari";
$place="Fatuha";
$age=12;
$expiry=time()+365*24*60*60;
$choices=(object)array("Name"=>$name, "Place"=>$place, "Age"=>$age);
$cookiename="C1";
$info=(object)array("info"=>$choices,"Expiry"=>$expiry);
setcookie($cookiename, json_encode($info), $expiry);
if(isset($_COOKIE['C1']))
{
$ck=json_decode($_COOKIE['C1']);
$n=$ck->info->Name;
$p=$ck->info->Place;
$a=$ck->info->Age;
$ex=$ck->Expiry;
echo 'Cookie data: <br>Name: ',$n,'<br>Place: ',$p,'<br>Age: ',$a,'<br>';
echo 'Expiry Date: ',date("Y-m-d H:i:s", $ex);
}
?>
Output
Similarly, another example of creating cookies is shown below.
<?php
$cn="C2";
$x=10;
$y=20;
$z=30;
$ex=time()+100*24*60*60;
$data=(object)array("A"=>$x, "B"=>$y, "C"=>$z);
$info=(object)array("Info"=>$data,"Expiry"=>$ex);
setcookie($cn, json_encode($info), $ex);
if(isset($_COOKIE['C2'])){
$c=json_decode($_COOKIE['C2']);
echo $c->Info->A,'<br>';
echo $c->Info->B,'<br>';
echo $c->Info->C,'<br>';
echo date("Y-m-d H:i:s", $c->Expiry),'<br>';
}
?>
Output