How to Use PHP Serialize() and Unserialize()

How to use php serialize() and unserialize()

A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.


Take for example this common problem:

How do I pass a PHP array to Javascript?

PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

Javascript can easily reverse this into an actual Javascript array.

This is just as valid a representation of the same data structure though:

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

But pretty much only PHP uses it, there's little support for this format anywhere else.

This is very common and well supported as well though:

<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>

There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.

serialize to unserialize data

You can just iterate over the array and unserialize every single entry:

$unserialized = array();

foreach ($data as $serialized) {
$unserialized[] = unserialize($serialized);
}

PHP - *fast* serialize/unserialize?

It seems that the answer to your question is no.

Even if you discover a "binary serialization format" option most likely even that would be to slow for what you envisage.

So, what you may have to look into using (as others have mentioned) is a database, memcached, or on online web service.

I'd like to add the following ideas as well:

  • caching of requests/responses
  • your PHP script does not shutdown but becomes a network server to answer queries
  • or, dare I say it, change the data structure and method of query you are currently using

PHP serialize and unserialize array not working?

As serialize() is not binary safe I'd suggest you to use json to encode you data:

$all = array (
"points" => '123',
"photo" => '写真',
"video" => 'video'
);
$sall = json_encode($all);
// {"points":"123","photo":"\u5199\u771f","video":"video"}

$decode = json_decode($sall, true);

/*array(3) {
["points"]=>
string(3) "123"
["photo"]=>
string(6) "写真"
["video"]=>
string(5) "video"
}*/

As a side note, if you started building something I'd suggest you move to MySQLi or PDO, mysql_* functions are deprecated. Here is a nice tutorial to get you started on PDO.

To get results:

$result = mysql_query("SELECT * FROM users WHERE uname='$uname'")
or die(mysql_error());

$row = mysql_fetch_assoc($result);

if($row) {
$lang = $row['lang'];
$orilang = json_decode($lang, true);
// orilang contains the array
echo $orilang['photo'];

// or
// $orilang = json_decode($lang);
// echo $orilang->photo;

} else {

}

How to serialize and unserialize an array with correct format

This is your correct array. If you want to print the array with structure use

<?php 
echo "<pre>",print_r($array),"</pre>";
?>

Read the manual http://php.net/manual/en/function.serialize.php as it will be explained. Here is an easy online generator where you can test if your array is valid for sirialize http://php.fnlist.com/php/serialize

EDIT

 <?php 

$permis =array(
'employee' => array(
'myprofile' => array(
'default' => '0', 'personal' => '0', 'job' => '0', 'leave' => '0', 'permission' => '0', 'bonus & commision' => '0', 'document' => '0', 'emergency contact' => '0', 'benifits' => '0'
),
'view emp' => array(
'default' => '0', 'personal' => '0', 'job' => '0', 'leave' => '0', 'permission' => '0', 'bonus & commision' => '0', 'document' => '0', 'emergency contact' => '0', 'benifits' => '0', 'notes' => '0', 'onboard' => '0', 'offboard' => '0', 'charts' => '0'
)
)
);

$serialized = serialize($permis);
echo "<pre>",print_r($serialized),"</pre>"; //echo serialized array

will output

a:1:{s:8:"employee";a:2:{s:9:"myprofile";a:9:{s:7:"default";s:1:"0";s:8:"personal";s:1:"0";s:3:"job";s:1:"0";s:5:"leave";s:1:"0";s:10:"permission";s:1:"0";s:17:"bonus & commision";s:1:"0";s:8:"document";s:1:"0";s:17:"emergency contact";s:1:"0";s:8:"benifits";s:1:"0";}s:8:"view emp";a:13:{s:7:"default";s:1:"0";s:8:"personal";s:1:"0";s:3:"job";s:1:"0";s:5:"leave";s:1:"0";s:10:"permission";s:1:"0";s:17:"bonus & commision";s:1:"0";s:8:"document";s:1:"0";s:17:"emergency contact";s:1:"0";s:8:"benifits";s:1:"0";s:5:"notes";s:1:"0";s:7:"onboard";s:1:"0";s:8:"offboard";s:1:"0";s:6:"charts";s:1:"0";}}}

 $unserialized = unserialize($serialized);
echo "<pre>",print_r($unserialized),"</pre>"; //echo unserialized array
?>

will output

array(
'employee' => array(
'myprofile' => array(
'default' => '0', 'personal' => '0', 'job' => '0', 'leave' => '0', 'permission' => '0', 'bonus & commision' => '0', 'document' => '0', 'emergency contact' => '0', 'benifits' => '0'
),
'view emp' => array(
'default' => '0', 'personal' => '0', 'job' => '0', 'leave' => '0', 'permission' => '0', 'bonus & commision' => '0', 'document' => '0', 'emergency contact' => '0', 'benifits' => '0', 'notes' => '0', 'onboard' => '0', 'offboard' => '0', 'charts' => '0'
)
)
);

I checked this twice. The array is correct and the unserialize is also correct.
http://php.fnlist.com/php/serialize
If you want to echo a key of the array use a foreach or something like this

<?php
echo $unserilized['employee']['myprofile']['personal'];

?>
will output

0 as it is the value of the key

How does object serialize/unserialize work?

PHP can know what to do at line#2 but how it knows what to do at line#5 which is a unserialized object? does it save the code as well?

Yes, serialize() will save the information about the class which this object is an instance of, along with its state, so when you unserialize, you get an instance of that class, which in this case is ClassName.

PHP Serialize & Unserialize

In your code:

<input type="hidden" name="strVid" value="<?php echo $serialized; ?>">

That's most certainly wrong, because the variable will contain double quotes; you must escape those:

<input type="hidden" name="strVid" value="<?php echo htmlspecialchars($serialized, ENT_QUOTES, 'UTF-8'); ?>">

Btw, this is assuming you're doing this to unserialize it:

$myNewArray = unserialize($_POST["strVid"]);

PHP Unserialize data for use in array - sub standard characters in string

PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.

It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.

Here's a fiddle

$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}

Outputs:

0) H592736029375 
1) K235098273598
2) B039571208517

Serialize/Unserialize javascript and be read by PHP

To make JavaScript serialize in the syntax of PHP's serialize would require a custom JavaScript function, however you can do what you want with JSON.

To serialize to JSON in JavaScript you would use the stringify method of the JSON object:

JSON.stringify(myArray)

and to unserialize a JSON string in PHP you would use json_decode:

json_decode($myJsonArray)

If you want to support older browsers, you will have to include an external implementation of the JSON object. See Browser-native JSON support



Related Topics



Leave a reply



Submit