I’ve had a problem today which was driving me nuts: Whenever I read out some serialized PHP data from a MySQL database, the unserialize() function refused to deserialize the data. When manually putting the same set of data into a textfile and reading it via file_get_contents(), the problem did not occur.

I did not exactly figure out, if the problem were the German Umlaute, which where contained within the text, in combination with a wrong DB charset, or some other character problems. Anywho, the comments at php.net finally set me straight: I encoded the data with base64_encode() before sending it to the database, reversing the stacking of functions in read operations.

Another problem is the fact, that unserialize() will return false if the deserialisation was unsucessfull, thus leaving you no chance to discriminate between a deserialization error and a correctly decoded false value. The following decode function also addresses that problem.

For your convenience, I’ve attached the two functions I used for de- and encoding:

/**
  * Internal function to put variables into a format which
  * can be stored in the database.
  * As a basis, serialize() is used, for storage
  * in SQL database, the  values are then base64 encoded
  * @param mixed $value The value to encode, needs to be processable by serialize
  * @return string Representation of value to use in database
  */
public function encodeValue($value){
    return base64_encode(serialize($value));
}
/**
 * Opposite of <em>encodeValue()</em>. This will also check, if deserialization
 * has worked, throwing an exception if not
 * @param $encodedValue String in format provided by <em>encodeValue()</em>
 * @return mixed The original value
 * @throws Exception If deserialization did not work.
 */
public function decodeValue($encodedValue){
    $decodedValue=base64_decode($encodedValue);
    $unserialized=unserialize($decodedValue);

    //check for faulty serialization
    if(unserialize($decodedValue)===false && $decodedValue!=serialize(false)){
        throw new Exception("Error while deserializing this: $decodedValue");
    }

    return $unserialized;
}