dou47278 2014-10-03 16:33
浏览 54
已采纳

当参数只是一个简单的字符串时,PHP反序列化偏移量错误

I am asking question after applied SO Ans.

i am trying to Unserialize from a serialized string fetched from DB.

I am getting Error : Unserialize offset error

I have two case

Same Code in both case:

 $categories = preg_replace( '!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'",  $data['Member']['category'] );        
 var_dump($categories);  
 $cat_unserialize = unserialize($categories);
 var_dump($cat_unserialize );  

case 1 : when

$data['Member']['category'] => Adventure Camps

case 1 : Error:

string 'Adventure Camps' (length=15)

Notice (8): unserialize(): Error at offset 0 of 15 bytes

boolean false

case 2 : when

$data['Member']['category'] => a:4:{i:0;s:9:"Adventure";i:1;s:12:"Sports ";i:2;s:15:"Training";i:3;s:29:"Educational";}

case 2 : No Error Code id Working Fine

  • 写回答

2条回答 默认 最新

  • duanliang789262 2014-10-03 16:39
    关注

    Unserialize only works on a serialized string. You need to prevent the notice from printing when trying to unserialize a string that isn't a serialized array.

    $cat_unserialize = @unserialize($categories);
    

    Otherwise, I'm not sure why it would be a problem.
    Then afterwards, before using the variable you can check if it's an array or string.

    if(is_array($cat_unserialize)) {
        //do something with array.
    }
    else {
        //do something with string.
    }
    

    Also, I don't understand the preg_replace(). Why remove the elements that make the string serialized, and then try to unserialize it?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度