Serialize And Unserialize With PHP

Monday, June 30, 2008 - 09:30

If you have an object or array that you want to save until a later you can use the serialize() and unserialize() functions. The operation of the functions are straightforward. To serialize() an array just pass the serialise function the array like this.

1
2
$array = array(1,2,3,4);
$serializedArray = serialize($array);

Now when we print the serialized array out we get the following.

a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;}

This contains all of the data needed to recreate our array. Be careful not to edit this string because it will not work if you want to unserialize it and get the array back. You can store this string in a file or a database so that you can recreate the exact same array at a later date.

If you do chose to store the serialized string in a database you might want to encode it as well. This is to stop the database encoding or removing any characters and destroying your array. To encode the string you can use the base64_encode function in this way.

$encodedSerializedArray = base64_encode(serialize($array));

This string now contains the following.

YTo0OntpOjA7aToxO2k6MTtpOjI7aToyO2k6MztpOjM7aTo0O30=

To get the array back again we use the unserialize() function like this. If you used the base64_encode() to encode the array then you can use the base64_decode() function to turn it back into an unserializable string again.

$array = unserialize($array);

The $array variable now contains our original array.

The same can also be done with objects in exactly the same way. The main difference is that PHP will try to call the __wakeup() function of the object (if it exists) once it has been reconstructed.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment