Learning Is Fun

Talks on Web Technology and Better Product Development

PHP: Serialization & Unserialization explanation, code & example

December31

Hello Folks!

When I was new to PHP 5 Object Oriented Programming (OOP), the serialization and un-serialization issues were not clear to me and I used to get confused with them often. Nowadays I can play with them easily and I will try to share my knowledge with you so that you can kill your confusion on these topics.

OK. Let us start!

What is Serialization?

This process makes a storable representation of a value that is useful for storing or passing PHP values around without losing their type and structure.

Remember the “__sleep” function in case of Serialization

Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method.

What is Unserialization?

This process takes a single serialized variable and converts it back into a PHP value.

Remember the “__wakeup” function in case of Unserialization

Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method.

What can you Serialize and Unserialize?

Many things as such

  1. Variables (Integer, Float, Real, String etc.)
  2. Arrays
  3. Objects etc.

What cannot you Serialize and Unserialize?

Only one type

  1. Resource-type

A simple example of Serialization and Unserialization

{code type=PHP}

require_once "class.serialize.php";
$myObject = new SerializationTest();
$myObject->counter = 999;
$myObject->myName = ‘Random Visitor’;
$myObject->myAge = 59;

$myString = ‘I am a simple line.’;
$myArray = array();
$myArray[0] = ‘One’;
$myArray[1] = ‘Two’;
$myArray[2] = ‘Three’;

echo $myString . ‘
‘;
var_dump($myArray);
echo ‘
‘;
echo ‘$myObject->counter: ‘ . $myObject->counter . ‘
‘;
echo ‘$myObject->myName: ‘ . $myObject->myName . ‘
‘;
echo ‘$myObject->myAge: ‘ . $myObject->myAge . ‘
‘;
var_dump($myObject);

$mySerializedString = serialize($myString);
$mySerializedArray = serialize($myArray);
$mySerializedObject = serialize($myObject);

$myString = ‘I have changed!’;
$myArray[0] = ‘New 1′;
$myArray[1] = ‘New 2′;
$myArray[2] = ‘New 3′;

echo ‘

‘;
echo $myString . ‘
‘;
var_dump($myArray);
echo ‘
‘;

$myUnserializedString = unserialize($mySerializedString);
$myUnserializedArray = unserialize($mySerializedArray);
$myUnserializedObject = unserialize($mySerializedObject);

echo ‘

‘;
echo $myUnserializedString . ‘
‘;
var_dump($myUnserializedArray);
echo ‘
‘;
echo ‘$myUnserializedObject->counter: ‘ . $myUnserializedObject->counter . ‘
‘;
echo ‘$myUnserializedObject->myName: ‘ . $myUnserializedObject->myName . ‘
‘;
echo ‘$myUnserializedObject->myAge: ‘ . $myUnserializedObject->myAge . ‘
‘;
var_dump($myUnserializedObject);

?>
{/code}

And here is the related class:

{code type=PHP}

class SerializationTest
{
public $counter;
public $myName;
public $myAge;
function __construct()
{
$this->counter = 100;
$this->myName = ‘Tanzilo Insido’;
$this->myAge = 28;
}

function __sleep()
{
echo “

__sleep()

“;
$this->counter = $this->counter + 1;
echo ‘Serialization Process Started!’ . ‘
‘;
echo ‘$this->counter: ‘ . $this->counter . ‘
‘;
return array(myString);
}

function __wakeup()
{
echo “

__wakeup()

“;
$this->counter = $this->counter – 1;
echo ‘UnSerialization Process Started!’ . ‘
‘;
echo ‘$this->counter: ‘ . $this->counter . ‘
‘;
}

}

?>
{/code}

Explanation of the example

If you notice the A to Z of the above code, you will find that we have a $myString variable, $myArray array and $myObject object. First of all, we have set values to them and then printed them all. They all perform as expected. Then we change all the values. Next when we serialize and unserialize the values, our original dara structure returns! And that is what we wanted.

Here is the result of the above code:

An interesting thing to note:
I would like to draw your attention to the fact that using __sleep() method, you can change the values of your declared and initialized variables. But you cannot change them by using __wakeup() function. For example, see the following code:

Now we serialize 3 (three)  times and unserialize 2 (two) times.

{code type=PHP}

require_once "class.serialize.php";
$myObject = new SerializationTest();

echo '

Start Value:

‘;
echo ‘$this->counter: ‘ . $myObject->counter . ‘
‘;
echo ‘$this->myString: ‘ . $myObject->myString;

$serializeData_1 = serialize($myObject);
$serializeData_2 = serialize($myObject);
$serializeData_3 = serialize($myObject);

$unSerializeData_1 = unserialize($serializeData_1);
$unSerializeData_2 = unserialize($serializeData_2);

?>
{/code}

And here is the result if we serialize 3 (three)  times and unserialize 2 (two) times.

Although we initialized $this->counter variable in the __construct() function, it is not used or has no effect in __wakeup() function. But it works properly in __sleep() or serialize() process. But what is the reason? The explanation is simple. The __wakeup() is part of the process when your data is retrieved from memory. Another thing is – did you notice the array return in the __sleep() function? Without returning this, the process often does not work. So, please remember to keep in your code.

You can download these small pieces of code files from here:
http://www.tanzilo.com/demo/code/serialize/serialize.zip

Thank you for reading.

posted under PHP
10 Comments to

“PHP: Serialization & Unserialization explanation, code & example”

  1. On February 13th, 2009 at 7:39 pm bobby dee Says:

    Now the confusion is dead, thank you for being a serialized confusion killer :) !

  2. On May 12th, 2009 at 6:31 am Man Says:

    Could you fix my unserialize code, plizz

    ==index.php
    <?php
    print”FAVOURITE COLOURS”;
    print”";
    print”Name : “;
    print”Colours :”;
    print”Red”;
    print”Blue”;
    print”Green”;
    print”White”;
    print”Size : S”;
    print”M”;
    print”L”;
    print”";
    print”";
    print”View Data“;
    ?>
    ==end script

    ==saveindex.php
    <?php
    $connect=mysql_connect(“localhost”,”root”,”yulisman”) or die (“Conn Failed”);

    $colors = serialize($chkColours);
    $sql=”insert into mycolors_tb (name,colors,size)
    values (‘$name’,'$colors’,'$size’)”;
    $qry=mysql_db_query(“mycolors_db”,$sql,$connect);

    if ($qry)
    { print “Data Saved”; }
    else
    { print “Save Failed”; }

    print”Main“;
    print”View Data“;
    ?>
    ==end script

    ==vdata.php
    <?php
    $connect=mysql_connect(“localhost”,”root”,”yulisman”) or die (“Conn Failed”);

    $query=”SELECT * FROM mycolors_tb ORDER BY noid ASC”;
    $doQuery=mysql_db_query(‘mycolors_db’,$query,$connect);
    $numrows=mysql_num_rows($doQuery);

    print “<table border=’1′”;
    print “No. ID”;
    print “Name”;
    print “Colours”;
    print “Size”;

    // can you make unserialize code for me, plizzz. I want 2 display the data in table
    // i tried, but the result is terrible

    while ($row=mysql_fetch_row($doQuery))
    {
    print “$row[0]“;
    print “$row[1]“;
    print”$row[2]“;
    print “$row[3]“;
    }
    print “”;
    ?>
    ==end script
    Thanks

  3. On November 12th, 2009 at 2:29 pm Amy Collins Says:

    You rock. Thanks so much for this explanation!

  4. On February 21st, 2010 at 2:41 pm sasasa Says:

    thanks for this memo about php serialize… it’s a good explaination… didn’t know about __sleep and __wakeup methods..

    I often use serialization in my job to store object in db, and more often to save lots of data in db when I don’t want to create a column for each data…

    I created a very simple tool to help me read serialized data, and to recover mis written serialized data (for example : truncated serialized token, etc.).. maybe this will help other people ;)

    http://unserialize.net

    C u,
    Marc

  5. On August 3rd, 2010 at 2:08 am cs Says:

    Hi, I would like to know if we are able to delete one of the object in the serailized data??

    thanks
    CS

  6. On February 21st, 2011 at 6:32 am Yogesh Says:

    Simple & easy tutorial of serialization,
    i just want for my project……thanks a Lot buddy..

  7. On December 7th, 2011 at 2:12 am Adam Says:

    very useful example to us. Thanks for your Great Job

  8. On December 11th, 2011 at 9:39 pm Buba Says:

    Thanks man! this solves the problem. Keep it up…

  9. On January 4th, 2012 at 7:11 am siva Says:

    pls explain why it is not produce unserialized output while use sleep and wakeup

  10. On January 26th, 2012 at 1:52 pm Ionel Says:

    When I try it I riceive the next error messages:

    ‘Use of undefined constant myString – assumed ‘myString’ in F:\wamp\www\class.serialize.php on line 19′

    follwed by:

    ‘serialize() [function.serialize]: “myString” returned as member variable from __sleep() but does not exist in F:\wamp\www\Serializ_Deserializ.php on line 21′

    What is wrong in my case since it works for all the others…?

Email will not be published

Website example

Your Comment: