Naresh
Naresh

Reputation: 2781

PHP Unserialize offset error when argument is only a simple string

I am asking question after applied SO Ans.

i am trying to Unserialize from a serialized string fetched from DB.

I am getting Error : Unserialize offset error

I have two case

Same Code in both case:

 $categories = preg_replace( '!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'",  $data['Member']['category'] );        
 var_dump($categories);  
 $cat_unserialize = unserialize($categories);
 var_dump($cat_unserialize );  

case 1 : when

$data['Member']['category'] => Adventure Camps

case 1 : Error:

string 'Adventure Camps' (length=15)

Notice (8): unserialize(): Error at offset 0 of 15 bytes

boolean false

case 2 : when

$data['Member']['category'] => a:4:{i:0;s:9:"Adventure";i:1;s:12:"Sports ";i:2;s:15:"Training";i:3;s:29:"Educational";}

case 2 : No Error Code id Working Fine

Upvotes: 0

Views: 1074

Answers (2)

mr12086
mr12086

Reputation: 1147

If you want the long option : this is from wordpress

<?php
function is_serialized( $data ) {
    // if it isn't a string, it isn't serialized
    if ( !is_string( $data ) )
        return false;
    $data = trim( $data );
    if ( 'N;' == $data )
        return true;
    if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
        return false;
    switch ( $badions[1] ) {
        case 'a' :
        case 'O' :
        case 's' :
            if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
                return true;
            break;
        case 'b' :
        case 'i' :
        case 'd' :
            if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
                return true;
            break;
    }
    return false;
}

Check to see if a string is serialized?

Upvotes: 0

Evadecaptcha
Evadecaptcha

Reputation: 1441

Unserialize only works on a serialized string. You need to prevent the notice from printing when trying to unserialize a string that isn't a serialized array.

$cat_unserialize = @unserialize($categories);

Otherwise, I'm not sure why it would be a problem.
Then afterwards, before using the variable you can check if it's an array or string.

if(is_array($cat_unserialize)) {
    //do something with array.
}
else {
    //do something with string.
}

Also, I don't understand the preg_replace(). Why remove the elements that make the string serialized, and then try to unserialize it?

Upvotes: 1

Related Questions