-
-
$string = 'O:6:「Foobar」:2:{s:3:「foo」; s:1:「1」;s:3:「bar」;s:1:「2」;}';
- $result = unserialize($string);
- var_dump($result); p>
/*
- object(__PHP_Incomplete_Class)[1]
- public '__PHP_Incomplete_Class_Name' => string 'Foobar' (length=6)
- public 'foo' => string 'foo'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() sload class class sloaded a. definition.
這不是什麼難事兒,只要做一次強制型別轉換,變成陣列就好了:
-
-
$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,例子如下:
-
-
-
-
-
-
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,就悲催了,比如說下面這段程式碼:
-
-
-
-
-
-
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出來:
-
-
-
-
-
-
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); ?>
複製代碼
不得不說,上面的程式碼真的很垃圾。提供大家一人我寫的:
-
-
-
-
-
-
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類,看起來是不是舒服多了。
|