Storing PHP arrays objects in a file or database – serialization and unserialization concept

Storing PHP arrays objects

Storing PHP arrays objectsHave you ever wanted to store directly an array or an object in a file or database and later get the array and object directly without having it reconstructed? Well, probably yes. While dealing with problems we often use arrays and objects. We might create the array or object on the fly or get some stored value and construct it using our own methods. While doing these, I’ve found, storing PHP arrays objects directly gives us not only ease of coding, but also ease of access for future use. But as we know, array and object both are abstract datatype and has to be somehow converted into the primitive datatypes (such as String) in order to store it inside a file or a database. Luckily we have functions in PHP to do these automatically. So let us see how to do this. But before we do, as usual:

Demo[download id=”20″ format=”1″]

#0: Understanding the concept:

Let us consider an array:

$array = array(
    'first_name' => 'Swashata',
    'last_name' => 'Ghosh',
    'email' => 'swashata [at] intechgrity [dot] com',
    'location' => 'India',
);

If we want to store that array in a database, then we can not do it directly, as none of the databases support such type of data. So, storing the array can be done either by breaking it into all it’s keys and storing the different strings inside some different table column of varchar type, or by somehow converting the whole array into some sort of encrypted string which can then be stored directly inside a database’s TEXT type column or inside a file. The same can later be used to decrypt and get the original data.

The first solution might seem easy for smaller examples, but in real world problems, where we have to deal with a big associative array with hundreds of keys, it would simply fail (imagine 100 columns in a database table). In such cases, let us see how we can use PHP’s in-built functions serialize and unserialize to make arrays and objects into something storable (strings) and get the original data (array, objects etc) from the stored string.

#1: Understanding the built-in functions:

#1.1: The serialize function:

As seen here, the serialize function does one good thing:

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

It accepts one parameter which can of any datatype, and returns a string which is the storable serialized value of the passed argument. We shall see its usage shortly.

#1.2: The unserialize function:

It does just the opposite of serialize. It takes a string input (which is supposed to be serialized), un-serializes it and returns the original data with original datatype. If a non-serialzied string is passed, then false is returned. Read more about it here.

unserialize() takes a single serialized variable and converts it back into a PHP value.

In short, it just takes one parameter (the serialized string) and can return any value of any datatype depending on the serialized string.

#2: Serializing using serialize:

Primitive datatypes such as integers, float, double, character, string etc, can be stored and retrieved without any special conversion (in databases and files). So there is no point on discussion about storing such data. We shall see how to make arrays and objects (two widely used abstract datatypes in almost any languages) storable.

#2.1: Serializing arrays:

So we take the array we were talking about. And we pass it through the serialize function and store the result.

$array = array(
    'first_name' => 'Swashata',
    'last_name' => 'Ghosh',
    'email' => 'swashata [at] intechgrity [dot] com',
    'location' => 'India',
);
echo '<h3>Before Serialization</h3>';
var_dump($array);

echo '<h3>After Serialization</h3>';
$serialized_array = serialize($array);
var_dump($serialized_array);

If we dump the two different variables, then the result is like:

array(4) {
  ["first_name"]=>
  string(8) "Swashata"
  ["last_name"]=>
  string(5) "Ghosh"
  ["email"]=>
  string(35) "swashata [at] intechgrity [dot] com"
  ["location"]=>
  string(5) "India"
}

 

string(149) "a:4:{s:10:"first_name";s:8:"Swashata";s:9:"last_name";s:5:"Ghosh";s:5:"email";s:35:"swashata [at] intechgrity [dot] com";s:8:"location";s:5:"India";}"

So we can see how an abstract datatype array is being converted into string which can be stored anywhere. We do not really need to worry about understanding the serialized string as there is another function (which we shall see shortly) to do the work for us.

#2.2: Serializing stdClass objects:

For the sake of simplicity let us create a stdClass object and store some data inside some of its member variables.

$object = new stdClass();
$object->first_name = 'Swashata';
$object->last_name = 'Ghosh';
$object->email = 'swashata [at] intechgrity [dot] com';
$object->location = 'India';

Now we simply pass the object variable through the serialize function and store the string.

echo '<h3>Before Serialization</h3>';
var_dump($object);

echo '<h3>After Serialization</h3>';
$serialized_object = serialize($object);
var_dump($serialized_object);

If we dump both the variables then we can see the result.

object(stdClass)#1 (4) {
  ["first_name"]=>
  string(8) "Swashata"
  ["last_name"]=>
  string(5) "Ghosh"
  ["email"]=>
  string(35) "swashata [at] intechgrity [dot] com"
  ["location"]=>
  string(5) "India"
}

 

string(162) "O:8:"stdClass":4:{s:10:"first_name";s:8:"Swashata";s:9:"last_name";s:5:"Ghosh";s:5:"email";s:35:"swashata [at] intechgrity [dot] com";s:8:"location";s:5:"India";}"

So once again, we have the converted another abstract datatype to some storable data.

#2.3: Serializing objects from custom class:

This is just same as before. The only thing is that the class should be visible from where we are trying to serialize one of its objects. Otherwise the serialization will be unsuccessful.

Let us start by creating a class:

/**
 * A dummy member class for this demo
 */
class member {

    /**
     * The first name of the member
     * @var string
     * @access private
     */
    private $first_name;

    /**
     * The last name of the member
     * @var string
     * @access private
     */
    private $last_name;

    /**
     * The email of the member
     * @var string
     * @access private
     */
    private $email;

    /**
     * The location of the member
     * @var string
     * @access private
     */
    private $location;

    /**
     * The constructor
     *
     * Sets either user provided values or default empty string to the member variables
     *
     * @param string $first_name The first name
     * @param string $last_name The last name
     * @param string $email The email
     * @param string $location The location
     */
    public function __construct($first_name = '', $last_name = '', $email = '', $location = '') {
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->email = $email;
        $this->location = $location;
    }

    /**
     * Get all the member information in an array
     *
     * @access public
     * @return array
     */
    public function get_information() {
        return array(
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'email' => $this->email,
            'location' => $this->location,
        );
    }

    /**
     * Set the member information
     *
     * @param string $first_name The first name
     * @param string $last_name The last name
     * @param string $email The email
     * @param string $location The location
     */
    public function set_information($first_name, $last_name, $email, $location) {
        $this->first_name = $first_name;
        $this->last_name = $last_name;
        $this->email = $email;
        $this->location = $location;
    }

}

Now we shall instantiate and set some values.

$my_member = new member();
$my_member->set_information('Swashata', 'Ghosh', 'swashata [at] intechgrity [dot] com', 'India');

Now we serialize and dump the variables.

echo '<h3>Before Serialization</h3>';
var_dump($my_member);

echo '<h3>After Serialization</h3>';
$serialized_my_member = serialize($my_member);
var_dump($serialized_my_member);

Which gives us out output as:

object(member)#3 (4) {
  ["first_name:private"]=>
  string(8) "Swashata"
  ["last_name:private"]=>
  string(5) "Ghosh"
  ["email:private"]=>
  string(35) "swashata [at] intechgrity [dot] com"
  ["location:private"]=>
  string(5) "India"
}

 

string(195) "O:6:"member":4:{s:18:"memberfirst_name";s:8:"Swashata";s:17:"memberlast_name";s:5:"Ghosh";s:13:"memberemail";s:35:"swashata [at] intechgrity [dot] com";s:16:"memberlocation";s:5:"India";}"

So yet again, the function successfully converted an object instantiated from our own class.

#3: UnSerializing using unserialize:

We use the serialize function, convert the abstract arrays and/or objects into string and store it somewhere. Now to get the stored serialized string and convert it into the original datatype, we shall use the unserialize function. Let us see a few examples.

#3.1: Unserialize array:

Previously we had our serialized array stored in $serialized_array variable. Let us pass it through unserialize function and store the value in some other variable.

echo '<h3>After UnSerialization</h3>';
$deserialized_array = unserialize($serialized_array);
var_dump($deserialized_array);

Now if we dump the unserialized variable the output would be

array(4) {
  ["first_name"]=>
  string(8) "Swashata"
  ["last_name"]=>
  string(5) "Ghosh"
  ["email"]=>
  string(35) "swashata [at] intechgrity [dot] com"
  ["location"]=>
  string(5) "India"
}

Same as the original one.

#3.2: Unserialize stdClass:

Unserializing objects from stdClass is pretty much straight forward. We simply pass the serialized string through unserialize.

echo '<h3>After UnSerialization</h3>';
$deserialized_object = unserialize($serialized_object);
var_dump($deserialized_object);

Now dumping the variable would give us output:

object(stdClass)#2 (4) {
  ["first_name"]=>
  string(8) "Swashata"
  ["last_name"]=>
  string(5) "Ghosh"
  ["email"]=>
  string(35) "swashata [at] intechgrity [dot] com"
  ["location"]=>
  string(5) "India"
}

Same as the original stdClass object. All the member variables are public as before and also they have the value we had stored.

#3.3: Unserialize custom class:

Here also the same restriction follows. The class whose serialized object is to be un-serialized should be visible while calling the unserialize function. We can do this by simply include – ing the class files. Read more about it here.

So assuming we have the presence of the class named member (which we had written before) we simply pass the serialized string through the unserialize function:

echo '<h3>After UnSerialization</h3>';
$deserialized_my_member = unserialize($serialized_my_member);
var_dump($deserialized_my_member);

Dumping would result into:

object(member)#4 (4) {
  ["first_name:private"]=>
  string(8) "Swashata"
  ["last_name:private"]=>
  string(5) "Ghosh"
  ["email:private"]=>
  string(35) "swashata [at] intechgrity [dot] com"
  ["location:private"]=>
  string(5) "India"
}

Which is obviously same as before. Now we can even call member methods from the unserialized object. So if we call the get_information method and dump it:

echo '<h3>Using method from unserialized object</h3>';
$my_member_information = $deserialized_my_member->get_information();
var_dump($my_member_information);

The output would be:

array(4) {
  ["first_name"]=>
  string(8) "Swashata"
  ["last_name"]=>
  string(5) "Ghosh"
  ["email"]=>
  string(35) "swashata [at] intechgrity [dot] com"
  ["location"]=>
  string(5) "India"
}

#4: Conclusion:

So we have seen how to use the serialize function to completely serialize any abstract datatype into storable strings. Then we can store the value in a file or in database for later use. To get the original function, we simply pass the serialized string into the unserialize function. So a quick recap would be:

  • Using serialize against arrays
  • Using serialize against stdClass and custom class objects
  • Using unserialize against arrays
  • Using unserialize against (The original class should be visible while unserializing the object else error would be produced).
Demo[download id=”20″ format=”1″]

That would be all. Hope you find it useful. We are eager to know how you are using these methods in your problem! So, just drop in a comment. If you have any trouble with anything, then don’t forget to ask.