YAS Global

PHP Serialize() & Unserialize() Issues

serialize( $value ) Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

To make the serialized string into a PHP value again, use unserialize().

If $value contains Double Quote(), Apostrophe(), Colon(:), or Semi-colon(;) and saves in the Database then the serialized value gets corrupted and unserialize() starts throwing error.

To avoid such issues, you can save the serialized value with base64_encode() in Database and while unserializing from Database, use base64_decode() as example shown below:

// to safely serialize
$save_in_db = base64_encode( serialize( $value ) );

// to unserialize value fetched from db...
$value = unserialize( base64_decode( $fetched_from_db) );

Cause of this issue

This issue mostly occurs when serialized data is not saved in Database correctly. Let’s suppose you are saving the serialized data like this:

$data = array( "hello", "world", "It's a test");
$saving_data = serialize( $data );
$sql_query = "UPDATE yasglobal SET data = '" . $saving_data . "' WHERE id = 1";

In the above example, your data gets corrupted while saving in database so when you try to unserialize your data it throws an error or returns nothing.

It all depends on how you are handling the data, like if you are using WordPress then it is better to save the data through the WordPress INSERT or UPDATE function.