How to test if a string is serialized data php

Very weird problem in the PHP world is testing if data is unserializable, because PHP throws a notice which passes the try…catch block and can for example stop Symfony commands. I saw a lot of very complicated solutions which analyze the strings and does very complicated logic to figure out if the string can successfully unserialize.  Kudos to the authors of those, I however wanted a simpler solution so I set a custom error handler in my function which catches the E_NOTICE and E_WARNING and throws an exception, then catch the exception if it exists and restore the handler. Get it? Got it? Good. Now lets see the actual code.

 

<?php
function isSerialized($data)
{
    set_error_handler(function($errno, $errstr){
        if($errno == E_WARNING) {
            throw new \Exception($errstr);
        } else if($errno == E_NOTICE) {
            throw new \Exception($errstr);
        }
    }, E_ALL);
    try
    {
        $unserialized = unserialize($data);
        return true;
    }
    catch(\Throwable $ex)
    {
        return false;
    }
    restore_error_handler();
}

 

About Pavel Petrov 2 Articles |  19 How-tos
Pavel is a senior developer for the last 7 years, with extended interest in Linux administration, WordPress and Symfony.

Be the first to comment

Leave a Reply

Your email address will not be published.


*