I have a file, “serialized.txt”, which contains a serialized array (created by doing serialize($array)).
s:133:"a:7:{i:0;i:640;i:1;i:480;i:2;i:2;i:3;s:24:"width="640" height="480"";s:4:"bits";i:8;s:8:"channels";i:3;s:4:"mime";s:10:"image/jpeg";}";
To fetch the contents I do:
$string = file_get_contents("serialized.txt");
Then I do:
print_r(unserialize($string));
The output that I get:
a:7:{i:0;i:640;i:1;i:480;i:2;i:2;i:3;s:24:"width="640" height="480"";s:4:"bits";i:8;s:8:"channels";i:3;s:4:"mime";s:10:"image/jpeg";}
This is the unserialized version of the string (contents of the file) when it should be printing the unserialized array. If I copy the string and do the following:
print_r(unserialize('a:7:{i:0;i:640;i:1;i:480;i:2;i:2;i:3;s:24:"width="640" height="480"";s:4:"bits";i:8;s:8:"channels";i:3;s:4:"mime";s:10:"image/jpeg";}'));
I get the correct output:
Array
(
[0] => 640
[1] => 480
[2] => 2
[3] => width="640" height="480"
[bits] => 8
[channels] => 3
[mime] => image/jpeg
)
So the problem seems to be isolated to the serialized array when pulling from the file.
According to the unserialize docs the function should be returning false if there is a problem; not the contents of the string.
The serialized data is taken from getimagesize and I have verified that if I serialize another array and place it into the file:
serialize(array("hi"));
I can successfully generate the output:
Array
(
[0] => hi
)
Are there any ideas why this may be happening? A bug with the serialization process relating to a getimagesize array, or potentially a “hidden” character in the file that my copy and paste removes? I have millions of these files already generated so it’s not possible for me to change the storage method. I guess the solution may just be to write my own parser to serialize the array? The input is always the same format so that’s plausible, but I would like to know of this a bug or my error with something somewhere.
As far as I can see your data is double serialized so the following code should print your array:
Although you should think about how you save to file. You may want to remove one serialization.
Does that solve your problem?