开发者

Check if string is serialized in PHP

开发者 https://www.devze.com 2022-12-30 21:30 出处:网络
I am in the middle of building a cache layer for the Redis DB to my application and I have come to the point where\'s it\'s about to take care of arrays.

I am in the middle of building a cache layer for the Redis DB to my application and I have come to the point where's it's about to take care of arrays.

I wonder if there's any good (high performance开发者_JAVA技巧!) way of controlling an string to be serialized or not with PHP?

Thanks a lot!


$array = @unserialize($string);
if ($array === false && $string !== 'b:0;') {
    // woops, that didn't appear to be anything serialized
}

The $string !== 'b:0;' checks to see if the serialized string may have been the value false. If this check is important to you you may want to trim the serialized string or otherwise preprocess it to make sure this works.


For those looking for alternative, this code worked for me as helper function for Laravel framework and then you can call it anywhere.

if(!function_exists('isSerialized')){
    function isSerialized($string){
        $tempString = '';
        $array = @unserialize($string);
        if(is_array($array)){
            foreach ($array as $k=>$i){
                //do something with data
                $tempString .= $k . $i['something'];
            }
        } else {
            $tempString = $string;
        }
        return $itemString;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号