在php中反序列化不返回任何值

时间:2014-12-25 07:20:50

标签: php kohana

我在字符串下面反序列化,但它没有返回任何内容。

  

一个:57:{S:10: “THEME_NAME”; S:5: “绿色”; S:16: “PUBLIC_ADS_LIMIT”; S:1: “5”; S:17: “PUBLIC_EDIT_LIMIT”; S: 1: “5”; S:8: “SITENAME”; S:10: “Abcdubai”; S:5:“;}

1 个答案:

答案 0 :(得分:1)

您要反序列化的数据是错误的

a:57{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}

如果您尝试使用错误报告E_ALL对其进行反序列化,您将看到通知

$data = 'a:57{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}';

var_dump($data);

你会得到

Notice: unserialize(): Error

,因为

  • a:57是数组长度,根据您拥有的数据显然不是57

  • s:指向字符串s:10:"Abcdubai"的长度,字符串Abcdubai长度不是10,因此您需要将其更改为s:8:"Abcdubai"

  • 最后,由于同样的原因,你最后有s:5:"; s:5表示长度为5个字符的字符串,并且只有一个双引号为空

    <?php
    // this the valid data
     $data = 'a:4:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:8:"Abcdubai";}';
    
    $data = unserialize($data);
    
    // accessing the valid serialized data
    echo $data['THEME_NAME'];
    echo $data['PUBLIC_ADS_LIMIT'];
    echo $data['PUBLIC_EDIT_LIMIT'];
    echo $data['SITENAME']; 
    

您可以尝试使用此方法来解决格式问题

   function fixUnserializeFormatting($data){
       // fix string length (will fix s:)
       $data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
       // remove empty matches with one double qoute
       $data = preg_replace('/s\:+[0-9]+\:";/i', '', $data);

       // trying to get the right array length
       $strings = substr_count($data,';') / 2;        
       // fixing array length
       $data = preg_replace('/^a:+[0-9]+:/i', "a:{$strings}:", $data);

       // finally returning the formatted data
       return $data;    
   }

用法

   $data = 'a:57:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}';

   $data = fixUnserializeFormatting($data);

   var_dump(unserialize($data));