6

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!) way of controlling an string to be serialized or not with PHP?

Thanks a lot!

Industrial
  • 41,400
  • 69
  • 194
  • 289
  • What do you mean? a string intern pool? PHP doesn't have that (yet) – Artefacto May 20 '10 at 22:18
  • I can't really tell what you're looking for from the wording of your question. The title made it sound like you just wanted a way to check if any given string is a serialized representation of something? – Chad Birch May 20 '10 at 22:18
  • Does this answer your question? [Check to see if a string is serialized?](https://stackoverflow.com/questions/1369936/check-to-see-if-a-string-is-serialized) – j08691 May 13 '20 at 13:57

2 Answers2

16
$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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • you don't have to take the risk, you can check error_get_last – Artefacto May 20 '10 at 22:26
  • 2
    @Artefacto This may or may not be useful, as it can be hard to tell whether the last error was really thrown here or sometime earlier. A better way may be to look at the serialized string to see if it looks like a single serialized `false`. Anyway, who serializes `false` values? ;) – deceze May 20 '10 at 22:31
  • Hi Deceze! Sounds great, I will definitely try that out! Have a great weekend! – Industrial May 21 '10 at 07:53
0

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;
    }
}
Nazari
  • 438
  • 1
  • 9
  • 20