Here’s what I was trying to do:
- serialize an array on one page (PHP: serialize($array))
- print out the results using
echoorprint_r - grab the serialized data from another script using
file_get_contents - unserialize that array so I could go about my business
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.

Thanks for the fix, worked out great for me. Kept getting that pesky “Error at offset” error.
I have been programming with PHP for at least 5 years and I have never come across this error until now. You mentioned you were using Codeigniter because this is the first time I have run into the error and I was using Expression Engine which is based on Codeigniter.
Again thanks for the tip. Using trim() worked great.
Comment by Joshua Powell — April 26, 2010 @ 9:06 pm
I just want to say Thanks,
The trim() solution did not work in my case, but your advice put me on the path to what I believe is at the heart of this problem- database field lenght. As it turns out, serialize() will include a few control characters with the data. If the field lenght is too small, those control characters will be truncated with no error from the system that they were not included with your data. As it is, the bug dont show up until you are trying to retrieve the data with the “unserialize()” function. Of course, with some of the control characters missing, the retrieval fails. This also explains, why trim() will work in some cases, depending on how much white space is can be removed with the trim(). For a permanent fix, increase the feild lenght in the database by a few characters to include the serialize control characters especially so if the data to be stored will vary in size.
Comment by Melli — May 17, 2010 @ 5:06 am