Php 简明教程

PHP – Filtered unserialize()

在 PHP 中,内置函数 unserialize() 可从 PHP 版本 4 开始使用。在 PHP 7 中,添加了一个传递允许类列表的条款。这允许过滤不受信任的源。unserialze() 函数仅反序列化来自可信类的 data。

In PHP, the built-in function unserialize() is available from PHP version 4 onwards. With PHP 7, a provision to pass a list of allowed classes has been added. This allows the untrusted source to be filtered out. The unserialze() function unserializes the data from only the trusted classes.

在 PHP 中,序列化表示生成值的存储表示。这对于存储或传递 PHP 值非常有用,而不会丢失它们的类型和结构。内置 serialize() 函数用于此目的。

In PHP, serialization means generation of a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure. The built-in serialize() function is used for this purpose.

serialize(mixed $value): string

unserialize() 函数从序列化的表示中给出一个 PHP 值。从 PHP 7 开始,unserialize() 函数遵循以下格式 -

The unserialze() function gives a PHP value from the serialized representation. From PHP 7 onwards, the unserialize() function follows the format below −

unserialize(string $data, array $options = [ ]): mixed

$data 参数是你想要反序列化的序列化字符串。

The $data parameter is the serialized string which you want to unserialize.

$options 参数已新引入。它是一个关联数组,具有以下键 -

The $options parameter has been newly introduced. It is an associative array of following keys −

Sr.No

Name & Description

1

allowed_classes an array of class names which should be accepted, or false to accept no classes, or true to accept all classes. Omitting this option is the same as defining it as true

2

max_depth The maximum depth of structures permitted during unserialization.

Example

请看以下示例:

Take a look at the following example −

<?php
   class MyClass {
      var int $x;
      function __construct(int $x) {
         $this->x = $x;
      }
   }
   class NewClass {
      var int $y;
      function __construct(int $y) {
         $this->y = $y;
      }
   }

   $obj1 = new MyClass(10);
   $obj2 = new NewClass(20);

   $sob1 = serialize($obj1);
   $sob2 = serialize($obj2);

   // default behaviour that accepts all classes
   // second argument can be ommited.
   // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object
   $usob1 = unserialize($sob1 , ["allowed_classes" => true]);

   // converts all objects into __PHP_Incomplete_Class object except those of MyClass and NewClass
   $usob2 = unserialize($sob2 , ["allowed_classes" => ["MyClass", "NewClass"]]);

   echo $usob1->x . PHP_EOL;
   echo $usob2->y . PHP_EOL;
?>

它将生成以下 output

It will produce the following output

10
20