PHP Serialize, What’s it Do? What’s it For?

by Terri Ann on May 11, 2008

I had seen this serialize and unserialize stuff before, in the Prototype library as well as PHP, I just never knew what it was for.

Then last month I spent a little bit of time playing with the Flickr API. I had had a really hard time with a fake API a client’s third party at work had given to us so I wanted to spend some time on my own learning about API’s, how they inherently work and what the real idea was.

{chitikaad}

Well, when deciding how I was going to receive data from Flickr I saw PHP Response as an option and started to look into it. Instead of receiving XML Flickr passed a serialized string that I just had to unserialize and POOF pre-constructed PHP object or array.

So that’s what serializing does!

Still had no idea how to practically apply it until yesterday while finalizing the updates to my WordPress Clipboard Express plugin. When I had originally created the plugin I had no idea how to make it multi-user, so I left it with all users having access to the dame data. I couldn’t release it that way and I had no idea how to feesably and reliably allow access to multiple users without creating 1000 new options every time a new user was created, I wanted to keep things neat and compact.

So I ended up creating an array for each user and serializing it before I stored it in the database. Then when I needed to pull the data out again I just had to unserialize it and drop the correct array values.


Example

I’ll give you an example using a simplified version of the ideas WordPress uses.

So I have three users in a table

--------------
| id | name  |
--------------
| 1  | Jane  |
| 2  | Larry |
| 4  | Bobby |
--------------

And I have all my options stored in another table

------------------------------------------------
| id | name              | value               |
------------------------------------------------
| 1  | blog_name         | this blog           |
| 2  | theme             | default-with-red    |
| 3  | user_settings     | 0010111001          |
| 5  | welcome_text      | welcome to the blog |
| 8  | clipboard_express |                     |
------------------------------------------------

I could have added 3 values to the options table clipboard_express1, clipboard_express2 and clipboard_express4 (numeric value to match the user’s id) or I could leave them all in one row and create an array to serialize.

The array might look like this:

<?php
    $clipboard[1] = "Hi I'm jane, and this is my clippy";
    $clipboard[4] = 'I\'ll add forms to my clipboard
            <input type="text" name="hello" value="Value here" />
            <input type="submit" name="submit" value="submit" />';
    $clipboard[2] = '';
?>

Then all I have to do is:

<?php
    $clip_serial = serialize($clipboard);
?>

It is strongly recommended that you use the mysqlrealescape_string() function to ensure your serialized value doesn’t mess up your table’s data. It’s also important to not for security purposes to help protect your database from a SQL Injection attack, though that’s more important when you’re coding the front and back end en entirety, still go to note! At least go read it people :)

{istockad}

And save clip_serial into the database. Now when I retrieve the data from the database I just grab the value.

<?php
    $serialized = $query_returned_array['value'];
    $clipboard_values = unserialized($serialized);

    /* Now
    echo $clipboard_values[4];
    displays: I'll add forms to my clipboard
            <input type="text" name="hello" value="Value here" />
            <input type="submit" name="submit" value="submit" />
    and
    echo $clipboard_values[1];
    displays: Hi I'm jane, and this is my clippy
    */
?>

Pretty neat huh?

In the database you’ll actually see this as the serialized value:

a:3:{i:1;s:34:"Hi I'm jane, and this is my clippy";i:4;s:145:"I'll add forms to my clipboard
        <input type="text" name="hello" value="Value here" />
        <input type="submit" name="submit" value="submit" />";i:2;s:0:"";}

Pretty neat way to store PHP in string to insert into a database then easily retrieve and re-PHPify. Actually it appears to me that it’s the only easy way, besides using PHP’s eval() function which would probably over-complicate things.

{ 11 comments… read them below or add one }

1 kapil March 6, 2009 at 6:15 am

You made it simple. Hats off

2 Anders July 7, 2009 at 4:45 pm

Thanks for explaining this.

3 sickbro November 5, 2009 at 9:44 am

Mate, this was just the information I was after. Thanks very much for your time writing this.

As a side note, unserialize() should NEVER be used on user input, as the security implications can be very serious. See SyScan / Blackhat USA 2009 and “Month of PHP Bugs”

Wow… I’m writing back to a 1 year old blog post lol

4 Mark Shercliff February 3, 2010 at 7:23 am

Best explanation I’ve read – thank you!

5 Marc February 21, 2010 at 4:45 pm

well explained !

here is a tool I often use in my job… to decode quickly serialized data… Indeed, serialised datas are good for system, but uneasy for us to read..

http://unserialize.net

Thanks again !

6 dreftymac February 22, 2010 at 9:31 pm

another alternative is to use base64 encoding to encode/decode the serialized data if you are worried about messing up your database values or transmitting the serialized data over the wire. disgustsuncoverakin_umbriel

7 Enigma415 March 10, 2010 at 3:18 am

I may add: if you wish to use these functions with client data ($GET & $POST, etc), preg_replace(‘/[^a-zA-Z0-9]‘, ”, $clientdata). That -should- make the sent string(s) safe for programmical use. Use that before you serialize() the data.

8 danilo di moia April 8, 2010 at 5:08 am

thanks for very clear explanation :)

9 Jules Manson May 23, 2010 at 1:51 pm

Please bare with me. This will only take one minute.

I created my own PHP template parser whereby my site uses one HTML template sprinkled with {TAGNAME} where tagname is actually different tag names that the parser will replace with functions or strings that I supply elsewhere or substitute data from MySQL database. This keeps my PHP completely separated from the HTML. All parser tags are also associated array elements. For example on my HTML template I have a tag {CRUMBS}. In a controller class I define this $tags['CRUMBS'] = “[php] return Breadcrumbs::inst();”; the inst() function simply instantiates my Breadcrumbs class. The “[php]” tells my template parser class to use the eval() function in order to treat the string as a PHP function. The end product of the function is to create a string that browsers recognize as several links of places visited on my site. My question is this: Could I have simply serialized the function instead of using eval()?

I hope I didn’t lose you.

10 Terri Ann June 3, 2010 at 4:23 pm

To be honest Jules you kind of lost me there. But even if you didn’t lose me on it I don’t think I have the answer to that question.

11 Jules Manson August 25, 2010 at 1:58 am

Thank y0u anyway and i figured it out myself. I loved your article and I now know what serialize is for. By the way the reason I am now responding is because once in a while I will google my name and survey past comments I have made at other sites. Its kind of neat to see one’s own web history.

Leave a Comment

Previous post:

Next post: