2017-09-02 82 views
0

对于这个问题,有没有比我找到的更好或更稳健的解决方案?如果反序列化()失败,则将新值赋给变量

$string = "a:1:{s:19:\"is_featured_service\";b:0;}"; 
    $unserialized_string = @unserialize($string); 

    if ($unserialized_string === false){ 
    $unserialized_string = 'another value'; 
    } 
+0

您的代码看起来很好。那么问题是什么? –

回答

1

我喜欢这个,因为你没有尝试剿错误:

/** 
* Check value to find if it is serialized data. 
* 
* Function borrowed from Wordpress. 
* 
* @param mixed $data Value to check to see if was serialized. 
* @return bool False if not serialized and true if it was. 
*/ 
function is_serialized($data) { 
    // if it isn't a string, it isn't serialized 
    if (! is_string($data)) 
     return false; 
    $data = trim($data); 
    if ('N;' == $data) 
     return true; 
    $length = strlen($data); 
    if ($length < 4) 
     return false; 
    if (':' !== $data[1]) 
     return false; 
    $lastc = $data[$length-1]; 
    if (';' !== $lastc && '}' !== $lastc) 
     return false; 
    $token = $data[0]; 
    switch ($token) { 
     case 's' : 
      if ('"' !== $data[$length-2]) 
       return false; 
     case 'a' : 
     case 'O' : 
      return (bool) preg_match("/^{$token}:[0-9]+:/s", $data); 
     case 'b' : 
     case 'i' : 
     case 'd' : 
      return (bool) preg_match("/^{$token}:[0-9.E-]+;\$/", $data); 
    } 
    return false; 
} 

$string = "a:1:{s:19:\"is_featured_service\";b:0;}"; 

$x = is_serialized($string) 
    ? unserialize($string) 
    : 'Some default value'; 
1

我只会保持@如果你不想处理错误,它看起来像你一样。然后将其更改为三元使其更小:

$unserialized_string = @unserialize($string) ?: 'another value';