php中serialize函数的bug

新作的程序采用了serialize()储存数组数据,偶尔发现,当数值中有某种字符时如分号、引号等,会使unserialize()的结果出问题,试过多种方法,最后无奈将数据用base64encode()函数处理,然后unserialize后用base64_decode解出,这样回避了某些符号与serialize的冲突。
  
  后来去php官方站,发现这确实有不少人遇到,并找到一个函数用来处理,方法与我的一样:
  
  <?php
  /*
  This is an array_walk style serialize that works with multi dimensional arrays, it also base64 encodes and decodes to allow '';'' to exist in the array.
   -- Alan Reddan
  */
  $data[qwerty] = "blah";
  $data[1][a] = "1aa";
  $data[2][b] = "2bb";
  $data[3][c] = ";;;;;;";
  
  //To Serialise Call :
  
  array_walk($data,''base64_encoder_multi'');
  $serialized_string = serialize($data);
  //print $serialized_string . ''\n''; //uncomment to see serialized array
  
  //To Unserialize Call
  
  $array = unserialize($serialized_string);
  array_walk($array,''base64_cleaner_multi'');
  
  print_r($array);
  //start functions
  function base64_encoder_multi(&$val,$key) {
     if (is_array($val)) array_walk($val,''base64_encoder_multi'',$new);
     else {
       $val = base64_encode($val);
     }
  }
  
  function base64_cleaner_multi(&$val,$key) {
     if (is_array($val)) array_walk($val,''base64_cleaner_multi'',$new);
     else {
       $val = base64_decode($val);
     }
  }
  //ends
  
  ?>

本文出自 “yun” 博客,谢绝转载!

你可能感兴趣的:(职场,bug,处理,Serialize,休闲)