Tuesday, June 4, 2013

PHP serialization of Arrays & Objects

Serializing in PHP is converting an Array or Object to storable String. This Serialized String can be used to store in databases,  the places where cannot pass data types except  String etc. After serializing an Array/Object, it actually encodes to a decodable string. This encoding is lack of human readability. 
To serialize, we can use serialize() method and to unserialize, unserialize().
.When storing data in SESSIONs, COOKIES, and passing data in HTML forms this method is more usefull.

Think you want to pass an Array from html form.



$user =  array(
    'name'=>'Alimankada Suwaris',
    'age'=>93,
    'city'=>'kimbissa',
    'birthday'=>'1892-05-11'
);


Traditionally you can assign hidden elements for each values.  But what will happen you want add more elements to the array. So it easy to searize this Array and pass it as a single hidden field.

$seriaziedUser = serialize($user);

//string 'a:4:{s:4:"name";s:18:"Alimankada Suwaris";s:3:"age";i:93;s:4:"city";s:8:"kimbissa";s:8:"birthday";s:10:"1892-05-11";}' (length=117)
<input type=”hidden” name=”user” value=”<?php echo $seriaziedUser; ?>” />

Because this serialized data contains quotes, this can be inturupt the data. So you might have to use htmlentities() before pass it through form.

DISADVANTAGES

it's really hard to work in SQL with that data : how do you write conditions on serialized data ? Even harder : how do you update it ? Do you really write a PHP script that fetches every lines, unserialize those, modifies them, re-serialize, and stores them back in DB L

the day you will want to migrate your data to another software, it'll require more work to migrate the data (if the new software is not written in PHP)

After requested data from html form,  the serialized data might not be unserializeble. Because if using of htmlentities(), the structure of serized data is alted.  So it should format to correct format and unserialize().

So web developers more prefers to use json_encode()  instead of serializing. Json encoded data have more advantages than serializing.
  • It’s more human readable.
  • Easy decoding & using.
  • Faster than serialize()
  • Flexible for more faltforms

This is json encoded string of our Array.

string '{"name":"Alimankada Suwaris","age":93,"city":"kimbissa","birthday":"1892-05-11"}' (length=80)
If we try to check performance of both functions.
$start = microtime(true);
$serializedArray = serialize($data);
$end = microtime(true);

echo $end-$start . '&lt;br/&gt;';

$start1 = microtime(true);
$jsonArray = json_encode($data);
$end2 = microtime(true);

echo  $end2-$start1;

1st round 
2.3841857910156E-5 :serialize
1.6927719116211E-5 :json

2nd round
2.7894973754883E-5 :serialize
2.0980834960938E-5 :json

3rd 
2.598762512207E-5 :serialize
2.0980834960938E-5 :json

So you can see every time json wins.

Thanks

1 comment:

Anonymous said...

Great job bro...