2012-10-02 45 views

回答

8

不,你不能抓到它,unserialize()不會拋出異常。

如果傳遞的字符串不是反序列化的,則返回FALSE併發出E_NOTICE。

您可以設置自定義異常處理程序來處理所有的錯誤:

function exception_error_handler($errno, $errstr, $errfile, $errline) { 
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline); 
} 
set_error_handler("exception_error_handler"); 
3

轉換所有PHP錯誤(警告通知等)例外。例子是here

9

的簡單方法是:

$ret = @unserialize($foo); 
if($ret === null){ 
    //Error case 
} 

但它不是最先進的解決方案。

最好的方法是如前所述有一個自定義的錯誤/異常處理程序(不僅爲這種情況)。但取決於你在做什麼,這可能是矯枉過正。

+2

每文檔:如果傳遞的字符串不unserializeable,則返回FALSE。幸運的是,很少有人會''serialize(false)' – gfaceless

+0

「如果傳遞的字符串不是非序列化的,則返回FALSE **併發出E_NOTICE **。 E_也被拋出。 – zedee

2

完整的解決方案看起來像下面這樣:

<?php 
// As mentioned in the top answer, we need to set up 
// some general error handling 
function exception_error_handler($errno, $errstr, $errfile, $errline) { 
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline); 
} 
set_error_handler("exception_error_handler"); 


// Note, there are two types of way it could fail, 
// the fail2 fail is when try to unserialise just 
// false, it should fail. Also note, what you 
// do when something fails is up to your app. 
// So replace var_dump("fail...") with your 
// own app logic for error handling 
function unserializeSensible($value) { 
    $caught = false; 
    try { 
     $unserialised = unserialize($value); 
    } catch(ErrorException $e) { 
     var_dump("fail"); 
     $caught = true; 
    } 
    // PHP doesn't have a try .. else block like Python 
    if(!$caught) { 
     if($unserialised === false && $value !== serialize(false)) { 
      var_dump("fail2"); 
     } else { 
      var_dump("pass"); 
      return $unserialised; 
     } 
    } 
} 

unserializeSensible('b:0;'); // Should pass 
unserializeSensible('b:1;'); // Should pass 
unserializeSensible('a:2:{s:1:"a";b:0;s:1:"b";s:3:"foo";}'); // Should pass 
unserializeSensible('a:2:{s:1:"a";b:0;s:1:"b";s:3:1111111111111111;}'); // Should fail 
unserializeSensible(123); // Should fail 
unserializeSensible("Gday"); // Should fail 
unserializeSensible(false); // Should fail2 
unserializeSensible(true); // Should fail