General

Notice: unserialize(): Error at offset

July 17, 2020 /1 min read

I was developing functionality in RecipePress WordPress theme of ours being sold on ThemeForest where I needed to save some recipes in cookies for users who are not logged in to the site. I came across this error where unserializing the saved $_COOKIE threw the following notice and returned false as bool value.

Notice: unserialize(): Error at offset 0 of 52 bytes

After googling it a lot, I found a solution which is to encode the serialized code using “base64_encode()” and then decode it using “base64_decode()” before unserializing it. The final result is given below.

The process of saving a serialized $_COOKIE

$safe_serialize = base64_encode( serialize( $inspiry_saved_recipes) );

if ( setcookie( 'inspiry_saved_recipes', $safe_serialize, time() + ( 60 * 60 * 24 * 30 ), '/' ) ) {
    esc_html_e( 'Recipe Saved', 'inspiry-recipe-press' );
}

The process of unserializing it back

if ( isset( $_COOKIE[ 'inspiry_saved_recipes' ] ) ) {
   $saved_recipes = $_COOKIE[ 'inspiry_saved_recipes' ];
   $saved_recipes = unserialize(base64_decode($saved_recipes));
   var_dump($saved_recipes);
}

It is necessary to give credit to the link which helped me in this regard. It was from the Magento forums and the link is given below.

https://magento.stackexchange.com/questions/247966/notice-unserialize-error-at-offset-0-of-94-bytes-magento-2-2-5-when-update-w

Leave a Comment

Let's build something exceptional.

I'm selectively available for consulting, security audits, plugin architecture, and product development partnerships. If you're building something that demands engineering excellence, I'd love to hear about it.

Fun Portfolio Projects

Cli Folio Comicbook Desktop Factory Game Folio Toons Folio