2

I tried to unserialize an serialized string:

$sri = 'a:8:{s:3:"key";s:32:"73b43c7df3604c8d725f856b219cffda";s:5:"email";s:19:"Aligh.Pro@gmail.com";s:4:"date";s:0:"";s:9:"user_info";a:4:{s:2:"id";i:2;s:5:"email";s:19:"Aligh.Pro@gmail.com";s:10:"first_name";s:5:"mahdi";s:8:"discount";s:4:"none";}s:9:"downloads";a:1:{i:0;a:3:{s:2:"id";i:44;s:8:"quantity";i:1;s:7:"options";a:2:{s:8:"quantity";i:1;s:8:"price_id";s:1:"1";}}}s:12:"cart_details";a:1:{i:0;a:10:{s:4:"name";s:17:"?????? ??";s:2:"id";i:44;s:11:"item_number";a:3:{s:2:"id";i:44;s:8:"quantity";i:1;s:7:"options";a:2:{s:8:"quantity";i:1;s:8:"price_id";s:1:"1";}}s:10:"item_price";d:20000;s:8:"quantity";i:1;s:8:"discount";d:0;s:8:"subtotal";d:20000;s:3:"tax";d:0;s:4:"fees";a:0:{}s:5:"price";d:20000;}}s:4:"fees";a:0:{}s:8:"currency";s:4:"RIAL";}';
$data_array = unserialize((string) $sri);
echo '<pre>';
print_r($data_array);
echo '</pre>';

but I saw this error: Notice: unserialize(): Error at offset 438 of 750 bytes in ...

I tried above serialized string by online unserialization. The string worked well. but in my cumputer, it doesn't.

what's the problem?

Mahdi98
  • 135
  • 1
  • 2
  • 8
  • `}}}s` there should be `,` definitelty. – u_mulder Jan 14 '18 at 13:30
  • the string `s:17:"?????? ??"` is not 17 Bytes long. After changing it to `s:9:"?????? ??"` unserialize worked (for me). I think, it's something with copy/paste and wrong encodings – akrys Jan 14 '18 at 13:43
  • Possible duplicate of [unserialize() \[function.unserialize\]: Error at offset](https://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset) – Ghlen Jan 14 '18 at 13:47
  • @u_mulder I did that it steal does'n work. – Mahdi98 Jan 14 '18 at 13:48
  • Because there are several occurences if this? – u_mulder Jan 14 '18 at 13:50

2 Answers2

7

Baba already wrote a great answer in this post. If you are in need of a quick fix, this code will do the job.

$data = preg_replace_callback(
    '!s:(\d+):"(.*?)";!', 
    function($m) { 
        return 's:'.strlen($m[2]).':"'.$m[2].'";'; 
    }, 
    $sri);

var_dump(unserialize($data));
Ghlen
  • 659
  • 4
  • 14
  • Worked perfectly, but still, i;m unable to understand that if the data is store via using serialize function, why wont it deserialize? why should we need this function? – Akshay Shrivastav Mar 17 '20 at 19:23
  • 1
    You need to understand that a serialization is essentially a way to store an object as a string. In the representation you have a section that tells php the upcoming part will be a certain amount of characters long. This amount was somehow wrong in your serialized string. This code simply recalculates the lengths of all the sections. I hope this helps. – Ghlen Apr 02 '20 at 12:10
1

Little addition to answer: regexp doesn't work on string containing line break characters. Something like

$sri = str_replace(["\n", "\r"], '', $sri);

should work fine.