但凡是一個合格的PHP程序員,就應該知道Unserialize與Autoload,但是要說起二者之間的關系,恐怕一清二楚的人就不多了。
說個例子,假設我們可以拿到第三方的序列化數據,但沒有相應的類定義,代碼如下:
<?php
$string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
$result = unserialize($string);
var_dump($result);
/*
object(__PHP_Incomplete_Class)[1]
public '__PHP_Incomplete_Class_Name' => string 'Foobar' (length=6)
public 'foo' => string '1' (length=1)
public 'bar' => string '2' (length=1)
*/
?>當我們反序列化一個對象時,如果對象的類定義不存在,那麼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.
這不是什麼難事兒,只要做一次強制類型轉換,變成數組就OK了:
<?php
$string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
$result = (array)unserialize($string);
var_dump($result);
/*
array
'__PHP_Incomplete_Class_Name' => string 'Foobar' (length=6)
'foo' => string '1' (length=1)
'bar' => string '2' (length=1)
*/
?>
不過如果系統激活了Autoload,情況會變得復雜些。順便插句話:PHP其實提供了一個名為unserialize_callback_func配置選項,但意思和autoload差不多,這裡就不介紹了,咱們就說autoload,例子如下:
<?php
spl_autoload_register(function($name) {
var_dump($name);
});
$string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
$result = (array)unserialize($string);
var_dump($result);
?>執行上面代碼會發現,spl_autoload_register被觸發了,多數時候這是有意義的,但如果遇到一個定義不當的spl_autoload_register,就悲催了,比如說下面這段代碼:
<?php
spl_autoload_register(function($name) {
include “/path/to/{$name}.php”;
});
$string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
$result = (array)unserialize($string);
var_dump($result);
?>
毫無疑問,因為找不到類定義文件,所以報錯 了!改改spl_autoload_register肯定行,但前提是你能改,如果涉及第三方代碼,我們就不能擅自做主了,此時我們需要一種方法讓 unserialize能繞開autoload,最簡單的方法是把我們需要的類FAKE出來:
<?php
spl_autoload_register(function($name) {
include “/path/to/{$name}.php”;
});
class Foobar {} // Oh, Shit!
$string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
$result = (array)unserialize($string);
var_dump($result);
?>不得不說,上面的代碼真的很狗屎!那怎麼做才好呢?我大致寫了一個實現:
<?php
spl_autoload_register(function($name) {
include “/path/to/{$name}.php”;
});
$string = 'O:6:“Foobar”:2:{s:3:“foo”;s:1:“1”;s:3:“bar”;s:1:“2”;}';
$functions = spl_autoload_functions();
foreach ($functions as $function) {
spl_autoload_unregister($function);
}
$result = (array)unserialize($string);
foreach ($functions as $function) {
spl_autoload_register($function);
}
var_dump($result);
?>代碼雖然多了點,但至少沒有FAKE類,看上去舒服多了。