4

在php中使用反序列化时,处理变量无法反序列化的潜在情况最安全的方法是什么。

例如(我不会这样做,只是为了举例):

$myVar = true;

$result = unserialize($myVar);

这将返回 false,这很好。但它也引发了令人讨厌的通知。

我一直在做以下事情:

$result = @unserialize($myVar);

感觉很hacky。那么当有可能出现错误时,反序列化的最佳方法是什么

4

1 回答 1

2

您可以使用带有 try / catch 的错误处理程序:

set_error_handler('exceptions_error_handler');
function exceptions_error_handler($severity, $message, $filename, $lineno) {
  if (error_reporting() == 0) {
    return;
  }
  if (error_reporting() & $severity) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
  }
}
$string = 'bob';
try {
   $result = unserialize($string);
} catch (Exception $e) {
   echo 'Caught exception: ',  $e->getMessage(), "\n";
}
if(isset($result)) {
    //Continue code for valid serialized array here
}
于 2012-12-20T21:49:41.257 回答