Dec 31, 2008 - PHP    11 Comments

PHP: Serialization & Unserialization explanation, code & example

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

And here is the related class:

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.

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:

Thank you for reading.


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

  • Could you fix my unserialize code, plizz

    print”Name : “;
    print”Colours :”;
    print”Size : S”;
    print”View Data“;
    ==end script

    $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’)”;

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

    print”View Data“;
    ==end script

    $connect=mysql_connect(“localhost”,”root”,”yulisman”) or die (“Conn Failed”);

    $query=”SELECT * FROM mycolors_tb ORDER BY noid ASC”;

    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[3]”;
    print “”;
    ==end script

  • You rock. Thanks so much for this explanation!

  • 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 😉

    C u,

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


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

  • very useful example to us. Thanks for your Great Job

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

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

  • 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…?

  • @Ionel : Just remove the “myString” inside the “array()” in the _sleep() and see 🙂 that just bcz we pass multiple serialize() [ie. 3 times in this case] but returning single serialize string [i.e myString] inside of array() 🙂

Got anything to say? Go ahead and leave a comment!