microtuts

PHP: Unserialize() Error at Offset… (Simple Solution)

Here’s what I was trying to do:

but I kept getting this error:

unserialize() [function.unserialize]: Error at offset 0 of 3457 bytes

I looked around and couldn’t find a simple a solution. I’m sure this error can occur in other ways, but I was trying with the simplest of arrays:

Array("Ryan" => "Bosinger");

My problem was that my echo statement was throwing some whitespace in there. That’s all. This fixed it:

$data["search_results"] = file_get_contents("http://localhost/sphider/search.php?query=" . $search_for . "&search=1&start=" . $start);
$result_string = trim($data["search_results"]);
$result_array = unserialize($result_string);

Basically, try trimming the whitespace before unserializing. Hope that helps!

Also, I was using Codeigniter but I really don’t think that has anything to do with it.


Creating your first programming language is easier than you think.

Understanding how a programming language works is a surefire way to be a better developer. Read more.


Suggested Reading


written by Ryan Bosinger
Ryan is a web developer living and working in Banff Alberta. He also writes for giftsforpeoplewitheverything.com and freefoley.com.

3 Responses to “PHP: Unserialize() Error at Offset… (Simple Solution)”

  1. Erik says:

    There’s really no good way to test if a string is serialized or not. Some stackoverflow article says it would return false, but in my case I ended up with the same error as you. Only a try/catch kept my app from throwing an error… :(

  2. Plamen Tetevensky says:

    Your output buffer already contains some leading data (zeros, \r, \n, etc.) from outside your opening php tag. For example, if you put <?php in your php file on the 3-rd line, you would have 2 '\r\n' not displayed when dumping the string. When echo-ing to output strict string, ensure your output buffer is clean:
    ….
    ob_clean(); // discard any data in the output buffer (if possible)
    flush(); // flush headers (if possible)
    echo $serialized_string;

  3. xx says:

    // my solution
    $check = @unserialize($variable->value);
    if ($check === FALSE && $variable->value != serialize(FALSE)) {
    $variables[$variable->name] = unserialize($variable->value);
    }

Leave a Reply