PHP Serialize and Unserialize Issue Returns False 2018

Advertisement

Welcome to 2018 first head bung of the year :-D, really, just this morning when I received a lot of emails from my client telling we’re in great great great great trouble and he sent me a bunch of foreach() code errors and I was like wow, “we really are in great trouble”.

So I started looking at the issue, and possibly what may cause it and viola it was a serialize data that is corrupted, thus unserializing it is not working and ended it just displays a foreach() error which my client is so afraid of :-D.

Enough for the story.

Let’s get started.

Walkaround

It turns out that it’s a decade issue, wew, so here shared his thought what may cause it and how we could possibly fix it, but unfortunately the solution won’t work on my end though, here’s why.

  • I have already tens to hundreds of data saved to the database and retrieving the old unencode data wouldn’t work.
  • I need to save a lot of disk space and encoding is not my choice

Hunting continues

What I really need is to simply fix the retrieval of the data or unserializing the data, regardless of what data being saved to the database, with or without quote or semi-colon in it.

Hurray

It turns out we can see the solution below


$formatted_details  = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $details ); 
$details            = unserialize( $formatted_details );

That’s it, happy coding ^_^

Advertisement