Home > Article > Backend Development > How can I store PHP arrays in cookies effectively?
Initial Problem: How do you properly store an array in a PHP cookie?
Solution 1: Storing Cookies as JSON
To preserve the array structure, convert the array to a JSON string:
<code class="php">setcookie('your_cookie_name', json_encode($info), time()+3600);</code>
Retrieve the cookie value:
<code class="php">$data = json_decode($_COOKIE['your_cookie_name'], true);</code>
Warning: Avoid using serialize/unserialize due to security issues.
Solution 2: Alternative Array Storage
Store array elements in individual cookies:
<code class="php">setcookie('my_array[0]', 'value1' , time()+3600); setcookie('my_array[1]', 'value2' , time()+3600); setcookie('my_array[2]', 'value3' , time()+3600);</code>
Access the array from $_COOKIE:
<code class="php">echo '<pre class="brush:php;toolbar:false">'; print_r( $_COOKIE ); die();</code>
This method relies on a PHP feature that treats cookie names containing array-like syntax as actual arrays.
The above is the detailed content of How can I store PHP arrays in cookies effectively?. For more information, please follow other related articles on the PHP Chinese website!