编程学习网 > 编程教程 > PHP7 教程
2016
09-20

PHP7过滤unserialize()

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

PHP7引入了过滤 unserialize()函数以在反序列化不受信任的数据对象时提供更好的安全性。它可以防止可能的代码注入,使开发人员能够使用序列化白名单类。

示例

<?php
class MyClass1 { 
   public $obj1prop;   
}
class MyClass2 {
   public $obj2prop;
}


$obj1 = new MyClass1();
$obj1->obj1prop = 1;
$obj2 = new MyClass2();
$obj2->obj2prop = 2;

$serializedObj1 = serialize($obj1);
$serializedObj2 = 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
$data = unserialize($serializedObj1 , ["allowed_classes" => true]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass1 and MyClass2
$data2 = unserialize($serializedObj2 , ["allowed_classes" => ["MyClass1", "MyClass2"]]);

print($data->obj1prop);
print("<br/>");
print($data2->obj2prop);
?>

这将在浏览器产生以下输出 -

1
2

扫码二维码 获取免费视频学习资料

编程学习