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.

  $choices=(object)array("Name"=>$name, "Place"=>$place, "Age"=>$age);
  setcookie($cookiename, json_encode($info), $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);


Example of A Cookie in PHP to Store User Data
Example of A Cookie in PHP to Store User Data

Similarly, another example of creating cookies is shown below.

  $data=(object)array("A"=>$x, "B"=>$y, "C"=>$z);
  setcookie($cn, json_encode($info), $ex);
        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>';  


A Cookie in PHP with an Expiry Date of 100 Days
A Cookie in PHP with an Expiry Date of 100 Days

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP