为了账号安全,请及时绑定邮箱和手机立即绑定

PHP手册中从5.5升级到5.6 unserialize函数怎么解释

PHP手册中从5.5升级到5.6 unserialize函数怎么解释

PHP
呼啦一阵风 2019-03-18 18:10:13
PHP手册中从5.5升级到5.6 unserialize的变更是这样写的: unserialize() will now fail if passed serialised data that has been manipulated to attempt to instantiate an object without calling its constructor. 英文比较差想知道是什么意思,传入的数据是序列化过的没有调用过constructor的对象? 我度过这样的代码,但没报错: class A{ } $reClass = new ReflectionClass('A'); $b = $reClass->newInstanceWithoutConstructor(); echo '<pre>'; print_r(unserialize(serialize($reClass))); die;
查看完整描述

1 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

这个问题其实是和序列化接口相关的一个修改。

5.6的更新日志里有写

5.6.0 Manipulating the serialised data by replacing C: with O: to force object instantiation without calling the constructor will now fail.

大意就是说,5.6不允许将修改已经序列化数据中的C:改为O:来避免调用类中生成器。

我们写一个类来了解这是什么意思,首先我们在PHP5.3中实现一个继承序列化接口的类

class obj implements Serializable {
    public $data;
    public function __construct() {
        $this->data = "My private data";
    }
    public function serialize() {
        return serialize($this->data);
    }
    public function unserialize($data) {
        echo 'test';
    }
}
  
$test = new obj();
echo serialize($test);//输出C:3:"obj":23:{s:15:"My private data";}

var_dump(unserialize('C:3:"obj":23:{s:15:"My private data";}'));//调用unserialize方法,输出test
var_dump(unserialize('O:3:"obj":1:{s:4:"data";s:15:"My private data";}'));//没有调用unserialize方法,没有输出

接下来我们在5.6中实验相同的代码

class obj implements Serializable {
    public $data;
    public function __construct() {
        $this->data = "My private data";
    }
    public function serialize() {
        return serialize($this->data);
    }
    public function unserialize($data) {
        echo 'test';
    }
}

$test = new obj();
echo serialize($test);//输出C:3:"obj":23:{s:15:"My private data";}

var_dump(unserialize('C:3:"obj":23:{s:15:"My private data";}'));//调用unserialize方法,输出test
var_dump(unserialize('O:3:"obj":1:{s:4:"data";s:15:"My private data";}'));//抛出了一个Warning,PHP Warning:  Erroneous data format for unserializing 'obj' 

所以其实这个更新的意思就是说,不能靠修改序列化的数据,在不调用对象构造器的情况下实例化对象

查看完整回答
反对 回复 2019-03-18
  • 1 回答
  • 0 关注
  • 509 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信