Nokka
Nokka

Reputation:

Why does unserialize in PHP keep returning false?

I've just written the easiest script in the world, but still I can't get it to work, and it's mighty strange.

I want to use jQuery to catch some input field values and serialize them with jQuery's serialize(). I then send the serialized string to the server to unserialize it. Here's the output I get from the serializing in jQuery, this is what I send to the server.

field1=value1&field2=value2&field3=value3

And here's the function,

public function unserialize_input()
{
    $str = $this->input->post("user_values");
    $unserialized = unserialize($str);
    var_dump($unserialized);
}

As I said, if I go "echo $str;" I get "field1=value1&field2=value2&field3=value3", so the string should be unserializable. However, I always get the same error message and the var_dump($unserialized); always returns bool(false).

Here's the error message I get from CodeIgniter, the framework I'm using for PHP.

Severity: Notice
Message: unserialize() [<ahref='function.unserialize'>function.unserialize</a>]: Error at offset 0 of 41 bytes

bool(false) 

I'm using MAMP and run this locally at the moment. I read something about magic_quotes_gpc being OFF could cause this locally, but it's enabled. What might be wrong?

Upvotes: 3

Views: 6019

Answers (3)

Marc Towler
Marc Towler

Reputation: 705

This is going to be a bit vague because I don't know jQuery overly well, but could it be that jQuery serialize's strings even slightly different from PHP? If so, then that would cause the error message that you see.

Upvotes: 0

Martijn Laarman
Martijn Laarman

Reputation: 13536

PHP's serialize and unserialize destruct and construct PHP objects/arrays/values.

jQuery serialize serializes a form into a POST string which can be very handy to do Ajax calls on. A post string is not a valid serialized string in PHP and cannot be reconstructed to a PHP mixed value and thus it returns false.

Upvotes: 4

Greg
Greg

Reputation: 321648

You're using the wrong PHP function. You should use parse_str instead.

 parse_str($str, $unserialized);

Upvotes: 8

Related Questions