opteronn
opteronn

Reputation: 176

unserialize() problem in php when serialize() works just fine

I'm using the serialize()/unserialize() functions in php 5.2. The text to be stored is POSTed via a form. Btw, no white-space before or after. Even if the text contains " or ', it serializes successfully. The problem is it does not unserialize() back. what am I doing wrong?

Upvotes: 5

Views: 13000

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 158007

It is magic quotes probably in response for such a behavior. So, to unserialize you may have to do a stripslashes() first:

if (get_magic_quotes_gpc()) $data = stripslashes($data);

though it's almost impossible to have magic quotes on a 5.2 system...
To say something certain, you have to find a difference between initial and returned data.

But anyway, why don't you use sessions instead of sending data to the browser and back? Sessions are a faster and secure way.

Upvotes: 4

Eclectic
Eclectic

Reputation: 847

David Walsh has a simple solution:

//to safely serialize  
$encoded_serialized_string = base64_encode(serialize($your_array));  

//to unserialize  
$array_restored = unserialize(base64_decode($encoded_serialized_string));  

http://davidwalsh.name/php-serialize-unserialize-issues

Upvotes: 10

Puneet Pugalia
Puneet Pugalia

Reputation: 1

Adding slashes to quotes solves the problem. Have a look at my code: http://codepad.org/7JWa2BT6

Upvotes: -1

Web Logic
Web Logic

Reputation:

When you serialize, you should use addslashes and when you unserialize, use stripslashes function.

Example:

if (get_magic_quotes_gpc())
{
  serialize($variable);
}
else
{
  addslashes(serialize($variable));
}

if (get_magic_quotes_gpc())
{
  stripslashes(unserialize($variable));
}
else
{
  unserialize($variable);
}

Upvotes: 0

Related Questions