Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is serialized in PHP

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!

like image 289
Industrial Avatar asked May 20 '10 22:05

Industrial


People also ask

Can strings be serialized?

String serialization is the process of writing a state of object into a byte stream. In python, the “pickle” library is used for enabling serialization. This module includes a powerful algorithm for serializing and de-serializing a Python object structure.

What is serialization in PHP with example?

Definition and Usage The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.

How can I serialize data in PHP?

To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.


1 Answers

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

like image 59
deceze Avatar answered Sep 26 '22 03:09

deceze