欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php中的Unserialize与Autoload

程序员文章站 2024-02-01 08:24:34
...
  1. $string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';

  2. $result = unserialize($string);
  3. var_dump($result);
  4. /*

  5. object(__PHP_Incomplete_Class)[1]
  6. public '__PHP_Incomplete_Class_Name' => string 'Foobar' (length=6)
  7. public 'foo' => string '1' (length=1)
  8. public 'bar' => string '2' (length=1)
  9. */
  10. ?>
复制代码

当反序列化一个对象时,如果对象的类定义不存在,那么PHP会引入一个未完成类的概念,即:__PHP_Incomplete_Class,此时虽然我们反序列化成功了,但还是无法访问对象中的数据,否则会出现如下报错信息: The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition.

这不是什么难事儿,只要做一次强制类型转换,变成数组就可以了:

  1. $string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';

  2. $result = (array)unserialize($string);
  3. var_dump($result);
  4. /*

  5. array
  6. '__PHP_Incomplete_Class_Name' => string 'Foobar' (length=6)
  7. 'foo' => string '1' (length=1)
  8. 'bar' => string '2' (length=1)
  9. */
  10. ?>
复制代码

不过如果系统激活了Autoload,情况会变得复杂些。顺便插句话:PHP其实提供了一个名为unserialize_callback_func配置选项,但意思和autoload差不多,这里就不介绍了,咱们就说autoload,例子如下:

  1. spl_autoload_register(function($name) {
  2. var_dump($name);
  3. });
  4. $string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
  5. $result = (array)unserialize($string);
  6. var_dump($result);
  7. ?>
复制代码

执行上面代码会发现,spl_autoload_register被触发了,多数时候这是有意义的,但如果遇到一个定义不当的spl_autoload_register,就悲催了,比如说下面这段代码:

  1. spl_autoload_register(function($name) {
  2. include “/path/to/{$name}.php”;
  3. });
  4. $string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
  5. $result = (array)unserialize($string);
  6. var_dump($result);
  7. ?>
复制代码

毫无疑问,因为找不到类定义文件,所以报错 了!改改spl_autoload_register肯定行,但前提是你能改,如果涉及第三方代码,我们就不能擅自做主了,此时我们需要一种方法让 unserialize能绕开autoload,最简单的方法是把我们需要的类FAKE出来:

  1. spl_autoload_register(function($name) {
  2. include “/path/to/{$name}.php”;
  3. });
  4. class Foobar {} // Oh, Shit!
  5. $string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
  6. $result = (array)unserialize($string);
  7. var_dump($result);
  8. ?>
复制代码

不得不说,上面的代码真的很垃圾。为大家提供一人我写的:

  1. spl_autoload_register(function($name) {

  2. include “/path/to/{$name}.php”;
  3. });
  4. $string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';

  5. $functions = spl_autoload_functions();
  6. foreach ($functions as $function) {
  7. spl_autoload_unregister($function);
  8. }
  9. $result = (array)unserialize($string);

  10. foreach ($functions as $function) {

  11. spl_autoload_register($function);
  12. }
  13. var_dump($result);
  14. ?>
复制代码

代码虽然多了点,但至少没有FAKE类,看上是不是舒服多了。