How is proper way to store an array in a cookie? in PHP Code example:
$number_ticket=2; $info[7][5]=1; $info[8][5]=1;
Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode ). Be aware that there is a limit on the length of the string you can store though.
Cookies can only store strings. Therefore, you need to convert your array of objects into a JSON string. If you have the JSON library, you can simply use JSON.
With PHP, you can both create and retrieve cookie values. The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name "user", a variable is automatically created called $user, containing the cookie value.
A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
To store the array values in cookie, first you need to convert them to string, so here is some options.
Storing code
setcookie('your_cookie_name', json_encode($info), time()+3600);
Reading code
$data = json_decode($_COOKIE['your_cookie_name'], true);
JSON can be good choose also if you need read cookie in front end with JavaScript.
Actually you can use any encrypt_array_to_string
/decrypt_array_from_string
methods group that will convert array to string and convert string back to same array. For example you can also use explode
/implode
for array of integers.
From PHP.net
Do not pass untrusted user input to unserialize().
- Anything that coming by HTTP including cookies is untrusted!
References related to security
setcookie('my_array[0]', 'value1' , time()+3600); setcookie('my_array[1]', 'value2' , time()+3600); setcookie('my_array[2]', 'value3' , time()+3600);
And after if you will print $_COOKIE
variable, you will see the following
echo '<pre>'; print_r( $_COOKIE ); die();
Array ( [my_array] => Array ( [0] => value1 [1] => value2 [2] => value3 ) )
This is documented PHP feature.
From PHP.net
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
Serialize data:
setcookie('cookie', serialize($info), time()+3600);
Then unserialize data:
$data = unserialize($_COOKIE['cookie'], ["allowed_classes" => false]);
After data, $info and $data will have the same content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With