I need to store some array data in a cookie and I have been researching the best way to do it, many people seem to say using serialize
is the way to go, but then in this thread:
PHP how to stringify array and store in cookie
..someone suggested against using it as "serialize will call constructor of a serialized class. This is bad because it can cause code execution."
So I'm wondering what other options I have? What about base64_encode
?
I can't use sessions
as I need to retain the data AFTER the browser is closed; though I am also worried about Cookies 4KB
limit.
FWIW I am storing shopping cart data of what is stored in someones cart, it needs to be loaded back in their cart when they come back.
How about generating a unique ID, storing it in a cookie, and storing your serialized array and the ID in database?
Example:
// ------------ STORING TO COOKIE AND DATABASE ------------ //
$id = uniqid();
setcookie("id", $id, time()+60*60*24); // 1 day
$serialized = serialize($array);
mysql_query("INSERT INTO yourTable (id, array) VALUES ('$id', '$serialized')");
// ------------ SELECTING FROM DATABASE ------------ //
if(!isset($_COOKIE['id'])) die();
$id = mysql_real_escape_string($_COOKIE['id']);
$result = mysql_query("SELECT array FROM yourTable WHERE id = $id LIMIT 1");
if(!is_resource($result)) die();
$serialized = mysql_result($result, 0);
$array = unserialize($serialized);
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