1
0

repair-serialized-string.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * dolphin. Collection of useful PHP skeletons.
  4. * Copyright (C) 2013 Johannes 'Banana' Keßler
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
  8. *
  9. * You should have received a copy of the
  10. * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11. * along with this program. If not, see http://www.sun.com/cddl/cddl.html
  12. */
  13. /**
  14. * how to "repair" an serilized string to get the data back.
  15. * it can not solve everything but it might help to recover some otherwise lost data
  16. */
  17. /**
  18. * the error message "Error at offset"
  19. * this inticates a malformed string. with the following method you can
  20. * find out where and what could be the error
  21. * At first use the exact offset from the error message and choose a length of 3
  22. * then you can get backwards and choose a longer range to identify the error
  23. * if you have utf-8 data, make sure you set the right encoding header.
  24. */
  25. var_export(substr($serializedStr, OFFSET, LENGTH););
  26. /**
  27. * there is a better way to store and save the data to avoid malformed data
  28. */
  29. $toDatabse = base64_encode(serialize($data)); // Save to database
  30. $fromDatabase = unserialize(base64_decode($data)); //Getting Save Format
  31. /**
  32. * finding the error in the serilized string.
  33. * based on a idea from stackoverflow
  34. *
  35. * @param string The serilized string
  36. */
  37. function findSerializeError($data1) {
  38. echo "<pre>";
  39. $data2 = preg_replace ( '!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'",$data1 );
  40. $max = (strlen ( $data1 ) > strlen ( $data2 )) ? strlen ( $data1 ) : strlen ( $data2 );
  41. echo $data1 . PHP_EOL;
  42. echo $data2 . PHP_EOL;
  43. for($i = 0; $i < $max; $i ++) {
  44. if (@$data1 {$i} !== @$data2 {$i}) {
  45. echo "Diffrence ", @$data1 {$i}, " != ", @$data2 {$i}, PHP_EOL;
  46. echo "\t-> ORD number ", ord ( @$data1 {$i} ), " != ", ord ( @$data2 {$i} ), PHP_EOL;
  47. echo "\t-> Line Number = $i" . PHP_EOL;
  48. $start = ($i - 20);
  49. $start = ($start < 0) ? 0 : $start;
  50. $length = 40;
  51. $point = $max - $i;
  52. if ($point < 20) {
  53. $rlength = 1;
  54. $rpoint = - $point;
  55. } else {
  56. $rpoint = $length - 20;
  57. $rlength = 1;
  58. }
  59. echo "\t-> Section Data1 = ", substr_replace ( substr ( $data1, $start, $length ), "<b style=\"color:green\">{$data1 {$i}}</b>", $rpoint, $rlength ), PHP_EOL;
  60. echo "\t-> Section Data2 = ", substr_replace ( substr ( $data2, $start, $length ), "<b style=\"color:red\">{$data2 {$i}}</b>", $rpoint, $rlength ), PHP_EOL;
  61. }
  62. }
  63. }
  64. ?>