PHP Serialization Issues

Source: Internet
Author: User
Tags object serialization

Serialization is the process of converting a variable into a string that can be saved or transmitted, and deserialization is the conversion of the string to the original variable at the appropriate time. Together, these two processes make it easy to store and transfer data, making the program more maintainable.

1. Serialize and Unserialize functions

These two are common functions for serializing and deserializing data in PHP.

<?php$a = Array (' a ' = = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut '); Serialized array $s = serialize ($a); echo $s;//output result: a:3:{s:1: "a"; S:5: "Apple"; s:1: "B"; S:6: "Banana"; s:1: "C"; s:7: "Coconut";}  Echo ' <br/><br/> ';//deserialization $o = unserialize ($s);p rint_r ($o);//output result Array ([a] + Apple [b] = banana [C] = Coconut)?>

  

Problems can occur when an array value contains characters such as double quotes, single quotes, or colons, which are deserialized. To overcome this problem, a clever trick is to use Base64_encode and Base64_decode.

$obj = Array ();
Serialization of
$s = Base64_encode (serialize ($obj));
Deserialization
$original = Unserialize (Base64_decode ($s));

But base64 encoding will increase the length of the string. To overcome this problem, you can use it with gzcompress.

Defines a function to serialize an object

function My_serialize ($obj)
{
Return Base64_encode (Gzcompress (Serialize ($obj)));
}

Deserialization
function My_unserialize ($txt)
{
Return Unserialize (Gzuncompress (Base64_decode ($txt)));
}

2. Json_encode and Json_decode

Serializing and deserializing using JSON format is a good choice:

    • Using Json_encode and Json_decode format output is much faster for serialize and unserialize formats.
    • The JSON format is readable.
    • The JSON format is smaller than the serialize return data result.
    • The JSON format is open and portable. It can also be used in other languages.

$a = Array (' a ' = = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ');

Serializing arrays
$s = json_encode ($a);
Echo $s;
Output: {"A": "Apple", "B": "Banana", "C": "Coconut"}

Echo ' <br/><br/> ';

Deserialization
$o = Json_decode ($s);

In the above example, the Json_encode output length is obviously shorter than the serialize output length in the previous example.

3. Var_export and Eval

The Var_export function outputs the variable as a string, and Eval executes the string as PHP code, deserializing the contents of the original variable.

$a = Array (' a ' = = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ');

Serializing arrays
$s = Var_export ($a, true);
Echo $s;
Output: Array (' a ' + = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ',)

Echo ' <br/><br/> ';

Deserialization
Eval (' $my _var= '. $s. ‘;‘);

Print_r ($my _var);

4. Wddx_serialize_value and WDDX Deserialize

The Wddx_serialize_value function can serialize array variables and output them as XML strings.

$a = Array (' a ' = = ' Apple ', ' b ' = ' banana ', ' c ' = ' Coconut ');

Serializing arrays
$s = wddx_serialize_value ($a);
Echo $s;

Output (view source of output String): <wddxpacket version= ' 1.0 ' >

Echo ' <br/><br/> ';

Deserialization
$o = Wddx_deserialize ($s);

Print_r ($o);
Output: Array ([a] = Apple [b] = Banana 1 = Coconut)

As you can see, there are more XML tag characters, resulting in a lot of space for serialization of this format.

Summary

All of the above functions perform normally when serializing array variables, but they are different when applied to objects. For example, the Json_encode serialization object fails. When deserializing an object, Unserialize and eval will have different effects.

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

PHP is still more commonly used, so I studied the PHP object serialization, here to share with you, hope to be useful to everyone. PHP object serialization is also a common feature that can serialize an object into a string that can be saved or transmitted. Let's look at an example first:

  1. Classtestclass
  2. {
  3. var$a;
  4. var$b;
  5. Functiontestclass ()
  6. {
  7. $this->a="Thisisa";
  8. $this->b="Thisisb";
  9. }
  10. Functiongeta ()
  11. {
  12. return$this->A;
  13. }
  14. FUNCTIONGETB ()
  15. {
  16. return$this->b;
  17. }
  18. }
  19. $obj=Newtestclass;
  20. $str=serialize($obj);
  21. ECHO$STR;

Output Result:

    1. O:9: "TestClass": 2:{s:1: "a"; S:9: "Thisisa"; s:1: "B"; S:9: "Thisisb";}

Let's analyze a string after the serialization of an object.

    1. O:9: "TestClass": 2:
    2. {
    3. S:1: "A"; S:9: "Thisisa";
    4. S:1: "B"; S:9: "Thisisb";
    5. }

First look at the content of the object itself: O:9: "TestClass": 2:o is a description of the object type (object), and then 9 is the name of the object to check the concentration, 2 is to represent the object has several properties. Looking at the contents of the two attributes: s:1: "a"; S:9: "Thisisa"; in fact, it is similar to the contents of an array, the first item: s:1: "A"; is the name of the attribute, the second item S:9: "Thisisa"; is the property value. The following properties are similar. First of all, a PHP object serialization application, the following is the PHP manual, the original text is not changed. Serialize () returns a string containing a byte stream representation of any value that can be stored in PHP. Unserialize () can use this string to reconstruct the original variable value. Using serialization to save an object can hold all the variables in the object. The function in the object is not saved, only the name of the class.

To be able to unserialize () an object, you need to define the class for that object. That is, if you serialize the object $ A of Class A in page1.php, you get a string that points to class A and contains the value of the variable in all $ A. If you want to serialize it in page2.php and rebuild the object $ A of Class A, you must have the definition of Class A in page2.php. This can be done, for example, by placing the definition of Class A in an include file and including this file in both page1.php and page2.php.

  1. <?php
  2. Classa.inc:
  3. ClassA
  4. {
  5. var$one =1;
  6. Functionshow_one ()
  7. {
  8. echo$this->one;
  9. }
  10. }
  11. page1.php:
  12. Include ("Classa.inc");
  13. $a=Newa;
  14. $S=serialize($a);
  15. Store $s somewhere so page2.php can find
  16. $fp=fopen("Store", "w");
  17. Fputs ($fp, $s);
  18. Fclose ($FP);
  19. page2.php:
  20. This line is required for normal deserialization
  21. Include ("Classa.inc");
  22. $S=implode("", @file ("store"));
  23. $a=unserialize($s);
  24. You can now use the Show_one () function of the $ A object
  25. $a->show_one ();
  26. ?>

When adding data to a group of several groups of cases, it is not always possible for each new group to add a new field, it is serialized to the field type of text (I set to text, because it is generally not known how many "groups") of the field, the time to deserialize the array is serialized out as the loop output line

When serializing an item, it can be very convenient, such as: the submission of a form, a data set, because the serialization will not have to care about the characters inside, is not injected and so on. The benefits are still many.

At least a disadvantage, the number of characters after serialization is more than before serialization, if you want to put a cookie to pay attention to the length, some characters also need to escape, put into the library, because the length is not certain, you must use the text field.



Serialization is the process of converting a variable into a string that can be saved or transmitted, and deserialization is the conversion of the string to the original variable at the appropriate time. Together, these two processes make it easy to store and transfer data, making the program more maintainable.

Serialization and deserialization in PHP are accomplished by using the functions serialize () and Unserialize (), respectively. The parameters of serialize () can be all variable types outside of the resource type, most commonly used to serialize the object, and Unseialize () deserializes the returned result of the serialize as a parameter to get the original object.

In PHP, serialization and deserialization can be used in many places! ~

For example: Database connections, serializing arrays, and so on.



Data aspects:
1: After upgrading to PHP5.5, json,serialize,igbinary three ways after serialization, the size does not change, the three format of the object structure has not changed, so you can seamlessly upgrade, msgpack because there is no previous data to do the comparison, temporarily unknown.
2: Occupy space, igbinary save obvious advantage, such as in JSON an array 5.4k size of data, serialize way to 8.6k, and use Igbinary way, only 2.4k, nearly 1 of Serialize way 4, but in the decimal group aspect Msgpack way more advantageous, igbinary occupies the space 123, but Msgpack Way is only 102. But in the case of large arrays, the obvious advantage of igbinary is more obvious. The large array igbinary wins, and the fractional group Msgpack wins.
Performance Aspects:
1: In small data, the performance of both JSON and native serialize is higher than the PHP5.3 version, while the performance is degraded when processing large amounts of data.
2: In the serialization aspect, the Msgpack mode performance is best, followed by Json_encode, again is igbinary, these two are similar, the worst is the native serialize, Native serialize performance consumption is about 1.4 times times the JSON and igbinary mode, but twice times the Msgpack way. In the large array, the serialization is convenient, basically with the decimal group, just igbinary performance teaching more json_encode way to improve. This round msgpack wins.
3: Igbinary in the inverse sequence than the serialization process faster, of course, but also the fastest, but this is also a cost, see the last note, the slowest json_decode way, guess the reason is that PHP as a server-side application, the most scene is encode, And decode the most common is the JS processing mode, performance is not very ideal. The Msgpack deserialization performance is basically twice times the serialization. This round igbinary wins.
4: Overall performance comparison, the overall performance is the sum of serialization and deserialization, a simple comparison will find that JSON is the worst, followed by the original serialize, again for the Igbinary way, the best for msgpack, but Igbinary and msgpack difference is really very small, In terms of space, small data msgpack win, Big Data igbinary win, is the same. Therefore, if the pursuit of extreme performance, you can consider the use of msgpack, if the use of space requirements are harsh, then choose the Igbinary way, it is estimated that this is phpredis to choose Igbinary as a reason for the built-in serialization, there is another reason, Consider that the Redis application scenario is more than a write-and-read, to ensure that the deserialization performance is high enough, non-igbinary mo.

The use of igbinary is not without cost, in the test we found that when calling Igbinary_unserialize, passing illegal data, will cause the entire PHP process to die, the log

[HTML]View Plaincopy
    1. Child 19131 exited on signal one (SIGSEGV) after 1.844938 seconds from start 1.844938 seconds from start
It is estimated that igbinary, in order to improve performance, did not validate the relevant format when unserialize, causing the entire process to exit unexpectedly. In the use of Redis, we use the serialize_php method of serialization, in order to improve performance, reduce the waste of Redis space using igbinary_serialize mode, and then switch accidentally stepped on this pit, resulting in server response error, direct 502, Fortunately, in the daily environment.

PHP Serialization Issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.