How to serialize strings with apostrophes using PHP
| By Matt Dunlap on May 17th, 2010 | 2 comments |
If not handled correctly, apostrophes will cause all kinds of problems when coding. Recently, I ran across a problem when trying to serialize an array of strings that could possibly have apostrophes. The solution is to encode to base64, then decode when reading the data.
One thing to note is that when you serialize the data as base64 you will not be able to read the data from the database due to the encoding. Of course this really isn’t a reason not to do this, and serialized data wasn’t that easy to read anyway.
Serialize
$data = "Hey, I have a special character's";
$insert_data = base64_encode(serialize($data));
Unserialize
$data = unserialize(base64_decode($insert_data));
That’s it. Took me a while to figure it out because I thought a simple “add_slashes” was going to take care of it… but it didn’t work.





Post a Comment