Back

How to fix issue with PHP serialization

Sometimes the serialized values in the database gets corrupted because of special characters present in the serialized data. The below function helps to fix those serialization problems

function mbUnserialize($string)
{
    try {
        $result = unserialize($string);
    } catch (\Exception $ex) {
        $string2 = preg_replace_callback(
            '!s:(\d+):"(.*?)";!s',
            function ($m) {
                $len = strlen($m[2]);
                $result = "s:$len:\"{$m[2]}\";";
                return $result;
            },
            $string
        );
        $result =  unserialize($string2);
    }

    return $result;
}

 

function mbFixSerialize($string)
{
    try {
        $goodString = unserialize($string);
    } catch (\Exception $exception) {
        $goodString = false;
    }


    if ( $goodString !== true &&  preg_match('/^[aOs]:/', $string) ) {
        $string = preg_replace_callback( '/s\:(\d+)\:\"(.*?)\";/s',    function($matches){return 's:'.strlen($matches[2]).':"'.$matches[2].'";'; },   $string );
    }
    return $string;
}
phpserializationissue

Latest Post

Information retrieval – Searching of text using Elasticsearch

Information retrieval is the process of obtaining relevant information resources from the collection of resources relevant to information need.

Learn more
© 2023 www.lamadly.com