Unserializing data doesn’t work

Been at this for the past 5 hours and I’m stumped. Tried the most ridiculous functions to try and fix it but to no avail.

I’m retrieving data from a WP database. The data has, before insert, had 1 array serialized using the serialize() function from PHP. It then gets inserted into WP database using the WP function update_user_meta. This function‘s reference says:

Read More
$meta_value
(mixed) (required) The new desired value of the meta_key, which must be different from the
existing value. Arrays and objects will be automatically serialized. 
Note that using objects may cause this bug to popup.
    Default: None

This made me think data may have been serialized twice. Though going through a whole lot of functions like unserialize(), array_map, json_decode, and combinations of these and more I have now got the below:

$i = 0;
while($i < count($fbData)){

    $someValue = $fbData[$i]['meta_value'];
    $usermeta = array_map( function( $a ){ return $a[0]; }, get_user_meta( $fbData[$i]['user_id'] ));
    if( $usermeta['facebookmeta'] ){
        $unserialized = unserialize( $usermeta['facebookmeta'] );
        //other methods tried: unserialize( unserialize
        // unserialize( json_decode(
        // json_decode( unserialize( json_decode(
        // json_decode( unserialize(
        // unserialize( array_map( 
        // unserialize( array_map( json_decode
        // whole lot others
        var_dump( $unserialized );
    }
$i++;
}

However this doesn’t work. This goes in with the $fbData:

'facebookmeta' => string 's:668:"a:16:{s:2:"id";s:9:"123456";s:4:"name";s:12:"Henkie";s:10:"first_name";s:4 //and so on

This is the result:

string 'a:16:{s:2:"id";s:9:"123456";s:4:"name";s:12:"Henkie";s:10:"first_name";s:4: //and so on

As is visible it from the result, it just removes the “s:668:"” from the start, which indicates it’s a 668 character string and leaves the remainder untouched.

How come the unserialization doesn’t work properly?

Related posts

Leave a Reply

3 comments

  1. Whoops found the answer! 🙂 WP function hidden in functions.php from WP themselves.

    function maybe_unserialize( $original ) {
        if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
            return @unserialize( $original );
        return $original;
    }
    

    Fixed the unserializing by doing:

    $unserialized = maybe_unserialize( unserialize( $usermeta['facebookmeta'] ));
    

    Returns it all in a neat array! 🙂

    Happy happy! 🙂

  2. I had the same problem with wp_options where custom post types have serialize data.
    I’ve figure that maybe there was a charset issue, and in fact… ta da!
    Try this:

    $unserialized = unserialize( utf8_encode($atest[0]['option_value'] ) );
    

    Where $atest[0] is thearray from mysql.
    Hope this helps!

    Aisfrond