learningtech
learningtech

Reputation: 33685

PHP unserialize problem

How come unserialize isn't restoring my array? See code below..

// prints a:1:{s:8:"txn_type";s:32:"recurring_payment_profile_cancel";}
echo $item['response']; 

// prints nothing
print_r(unserialize($item['response']));

I understand why the print_r($response) gives me nothing

** edit - I noticed this

Notice: unserialize() [function.unserialize]: Error at offset 6 of 2797 bytes in /home/reitinve/public_html/action/doc.php on line 13

What does that mean?

Upvotes: 6

Views: 8911

Answers (4)

Jivago
Jivago

Reputation: 826

Also be careful if you ever try to put a serialized array in a textarea, to eventually pass it somewhere else via Ajax, you may encouter problems with special characters like the Ampersand (&) that will be convertsed to "&", and this is enough for your "serialized" array not to restore.

I found the use of rawurlencode and rawurldecode very helpful to make my serialization bulletproof, no matter how it is carried across my scripts;

$myArray = array("Bugs Bunny", "Tom & Jerry");

$serialized = rawurlencode(serialize($myArray));

$myUnserializedArray = rawurldecode(unserialize($serialized));

Upvotes: 0

kubilay
kubilay

Reputation: 5330

Here's why I had this problem and how I worked it out:

I was storing an array in my input similar to this:

value="<?php echo htmlspecialchars(serialize(array($a, $b))); ?>"

Here, I had to use htmlspecialchars() because of possible parse errors.

Then when I tried to unserialize, it gave me this Error at offset X of Y bytes in ... error. I printed the unserialized string to screen, realized that html equivalents of some characters was causing the error.

To be more clear, double quotes html codes %22 was causing this error. So I replaced them back with quote chars and it worked.

unserialize(str_replace('%22', '"', $_POST['serialized']));

So it's better to check if there's any html codes in the serialized string and replace them back with original characters.

Upvotes: 0

Greg
Greg

Reputation: 321638

Is it possible $item['response'] contains some whitespace before or after it?

Check strlen($item['response']) gives you 61.

Edit: It seems to work with whitespace at the end, but whitespace at the start will make it fail to unserialize.

Edit: that error message means either you have a LOT of whitespace (almost 2kb of it), or $item['response'] is being changed between the echo and the unserialize

Upvotes: 3

SilentGhost
SilentGhost

Reputation: 319601

works for me just fine. are you sure that $item['response'] is a string? yeah, seems like leading whitespaces.

and on your dev server php never should give you 'nothing'. it should be configured to produce all errors, warnings and notices. also you can use http://php.net/var_dump instead of print_r as it give you more information.

Upvotes: 1

Related Questions