Imagine this:

  • Form data contains an apostrophe
  • Form gets submitted
  • POST data gets serialized
  • POST data is written to database
  • Database data is retrieved
  • Data cannot be unserialized

The problem is found in the serialized data. I tried without and with an apostrophe:

  • s:7:"company";s:12:"Joes company"
  • s:7:"company";s:14:"Joe's company"

I know POST data adds slashes to quotes and apostrophes but somewhere my slashes are being removed which is breaking the serialization. I'm not using the stripslashes() function anywhere - any ideas?


If you are writing serialized data into the db and not making use of any relations or advanced db functionality, you can simply base64 encode the serialized data before inserting into db, and decode when reading back.

+1  A: 

Are you sure the slashes are getting added? That only happens if Magic Quotes is enabled.

Magic Quotes is enabled, and the slashes are added. I have narrowed down to the following: in my SQL query, I surround the values with apostrophes. Try the following and you will see that " $test = '"company";s:14:"Joe\'s company"'; echo $test; " returns the string WITHOUT the slash. This is why the slash is not present once in the DB. But since the serialized string has quotes and apostrophes, how do I insert into the DB without using either?!
I've found the solution. Even though Magic Quotes adds a slash to POST data, you must do a further addslashes() to the serialized string so it can be added to the database, closed by either quotes or apostrophes. Once the value is retrieved from the DB and unserialized, stripslashes() can be used.
As an answer to your first question: use a prepared statement, check out mysqli or pdo.