douqixia7942 2017-04-26 18:59
浏览 101

jQuery反序列化由PHP序列化的数据

How can I unserialize data in jQuery? remember data is Serialized by PHP. Below is given example.

a:2:{i:0;s:9:" img1.jpeg";i:1;s:9:"img2.jpeg";}
  • 写回答

1条回答 默认 最新

  • donpvtzuux37724 2017-04-26 20:23
    关注

    This can be achieved using unserialize and json_encode

    $unserialized = unserialize($serialized_from_db);
    echo json_encode($unserialized);
    

    But please note your sample provided: s:9:" img1.jpeg" this part is incorrect. The s:9 means it expects string to be 9 bytes (this link provides a good guide on understanding output from serialize), however " img1.jpeg has a space and therefore is 10 bytes and fails: demo failing. You can add a check to see if this failes to unserialize:

    if ($unserialized === false)
    

    When you fix the incorrect part to: s:9:"img1.jpeg, giving you:

    a:2:{i:0;s:9:"img1.jpeg";i:1;s:9:"img2.jpeg";}
    

    will now work, see demo.

    At the end of the day I would recommend as others have above, to store json_encoded values in your database rather than serialized values.

    I came up with a really hacky hack to potentially fix bad serialized data:

    <?php
    function hackFixUnserialized($unserialized_string) {
      $parts = explode(';', $unserialized_string);
      foreach ($parts as &$part) {
        $kv = explode(':', $part);
    
        if ($kv[0] == 's') {
          $str_without_quotes = str_replace('"', '', $kv[2]);
          if ($kv[1] != strlen($str_without_quotes)) {
            $kv[1] = strlen($str_without_quotes);
          }
        }
    
        $part = implode(':', $kv);
      }
    
      return implode(';', $parts);
    }
    
    $unserialized_from_db = <<<EOT
    a:2:{i:0;s:9:" img1.jpeg";i:1;s:9:"img2.jpeg";}
    EOT;
    
    $unserialized = unserialize($unserialized_from_db);
    if ($unserialized === false) {
      $hack_fix = hackFixUnserialized($unserialized_from_db);
      printf('bad unserialized, fixed to: %s%s', $hack_fix, PHP_EOL);
      $unserialized = unserialize($hack_fix);
    
    }
    
    echo json_encode($unserialized);
    

    Demo of it here: https://eval.in/783408

    Hope this helps

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?