Cannot unserialize object after storing it seriali

2020-06-22 05:07发布

问题:

I'm trying to store a complex object here and am doing that by serialising the object running a mysql_real_escape_string on it and inserting it into a mysql database.

However when I retrieve it running a sql query - I'm using Zend frameworks Zend_DB_Table here but anyway - and when I try to stripslashes and unserialize I dont get my object back. I've tried to just unserialize without stripping slashes and all but nothings working.


UPDATE

This is weird. I made a simple page which just unserializes a serialised object. If I take the serialized string as it is retrieved from the database and unserialize it via this other page which just has an unserialize() on it - it works perfectly and I get my object back. However in the code where ironically I'm retriving the string and I run the exact same unserialize option there ,its not working!

So basically there is nothing wrong with the serialized string - for some weird reason it won't unserialize it in my application but it unserializes somewhere else, it makes no sense.

回答1:

You probably need to run it through base64 encoding first:

$safe_string_to_store = base64_encode(serialize($data));

Then to get it back out:

$date = unserialize(base64_decode($safe_string_to_store));

Try that and let us know if it works.

(and dont run stripslashes on it - there is no need to)



回答2:

You shouldn't run stripslashes on it - the database will give you back the right string to put into unserialize.

Make sure you have notices turned on and echo the string before you unserialize it - does it look right?



回答3:

You should be able to just do the following:

Assuming MyTable is your instance of Zend_Db_Table_Abstract:

$t = new MyTable();
$n = $t->createRow();
$n->serializedfield = serialize($data);
$n->save();

and let Zend DB take care of the escaping for you.

If you're doing it via an insert(), you shouldnt need to do anything either (the above uses insert())

Otherwise use $db->quoteInto() like

$db->quoteInto('INSERT INTO mytable (serializedfield) values (?)', serialize($data));


回答4:

I strongly recommend you to use json_encode instead of serialize. Some day you will find yourself trying to use that data from another place that is not PHP and having it stored in JSON makes it readable everywhere; virtually every language supports decoding JSON and is a well stablished standard. And is even worse if you base64 it, you also make the serialized content unreadable from your database console client.