Home > Article > Backend Development > How to use cookies to store value in php
The value value in Cookie can only add string data set to String type, but when we need to add other types of data such as arrays, json strings, etc., we must first convert the data and then save it. into the cookie.
Cookie stores arrays. There are many ways for cookies to store array type data. The essence is to talk about array conversion. into a string and then stored. (Recommended learning: PHP programming from entry to proficiency)
Use commas to concatenate the values of the array into a string, and then store the string in the cookie. When reading, you can use split() to split the string with commas and reassemble it into an array.
$data = array( 'a'=>'aaa', 'b'=>'bbb', 'c'=>'ccc' ); $str = $data['a'].",".$data['b'].",".$data['c']; //拼接成字符串 set_cookie('name',$str,3600); $cstr = $_COOKIE['name']; $cdata = split('[/,]',$cstr);
Cookie stores json string, use json_encode() to convert the array into a json string, then store the json string in the cookie, and finally use json_decode() to convert it back That’s it.
$data = array( 'a'=>'aaa', 'b'=>'bbb', 'c'=>'ccc' ); set_cookie('name',json_encode($data),time()+3600); $cstr = $_COOKIE['name']; $cdata = json_decode($cstr);
The above is the detailed content of How to use cookies to store value in php. For more information, please follow other related articles on the PHP Chinese website!