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

<?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 . '<br />';
	var_dump($myArray);
	echo '<br />';
	echo '$myObject->counter: ' . $myObject->counter . '<br />';
	echo '$myObject->myName: ' . $myObject->myName . '<br />';
	echo '$myObject->myAge: ' . $myObject->myAge . '<br />';
	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 '<br /><br />';
	echo $myString . '<br />';
	var_dump($myArray);
	echo '<br />';
	$myUnserializedString = unserialize($mySerializedString);
	$myUnserializedArray = unserialize($mySerializedArray);
	$myUnserializedObject = unserialize($mySerializedObject);
	echo '<br /><br />';
	echo $myUnserializedString . '<br />';
	var_dump($myUnserializedArray);
	echo '<br />';
	echo '$myUnserializedObject->counter: ' . $myUnserializedObject->counter . '<br />';
	echo '$myUnserializedObject->myName: ' . $myUnserializedObject->myName . '<br />';
	echo '$myUnserializedObject->myAge: ' . $myUnserializedObject->myAge . '<br />';
	var_dump($myUnserializedObject);
?>

And here is the related class:

<?php
	class SerializationTest
	{
		public $counter;
		public $myName;
		public $myAge;
		function __construct()
		{
			$this->counter = 100;
			$this->myName  = 'Tanzilo Insido';
			$this->myAge   = 28;
		}
		function __sleep()
		{
			echo "<h3>__sleep()</h3>";
			$this->counter = $this->counter + 1;
			echo 'Serialization Process Started!' . '<br />';
			echo '$this->counter: ' . $this->counter .  '<br />';
			return array(myString);
		}
		function __wakeup()
		{
			echo "<h3>__wakeup()</h3>";
			$this->counter = $this->counter - 1;
			echo 'UnSerialization Process Started!' . '<br />';
			echo '$this->counter: ' . $this->counter .  '<br />';
		}
	}
?>

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.

<?php
	require_once "class.serialize.php";
	$myObject = new SerializationTest();
	echo '<h3>Start Value:</h3>';
	echo '$this->counter: ' . $myObject->counter . '<br />';
	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);
?>

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.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
posted under PHP
4 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

Email will not be published

Website example

Your Comment: