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


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.

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 :)

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.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


55 kittens will go hungry today unless you
subscribe to the Ninedays Blog feed!
* We are no long in affiliation with bonsai kittens.
Similar Entries
MySQL Queries Made Easy With PHP Functions Library
Every web developer has a library of code that they reference frequently, if not constantly. I'm sharing with you one of my most useful snippets my MySQL helper class that helps me organize my queries and easily reference commonly used functions.
Multiple Select Drop Down Menu in PHP
It's very easy to take what we did back in January for reusable PHP drop down menu code and make it work for multi value select elements.
US Census Data as a MySQL Database Playground
Somehow I ended up at the 1990 US census and I realized what a valuable data resource it is! All kinds of data that I can use to make a well structured MySQL playground to test new scripts and ideas on.
From Query String to Cookie with JavaScript
Take a query string and save the values to a cookie using JavaScript. A perfect solution for tracking query string's values throughout a site that isn't using any server side scripting.
Birthday MySQL Query Hates Timestamps
In order to query the users with birthdays from my MySQL table I had to convert Unix timestamps saved as integers to a more usable DATETIME format, then we explore two ways to query the birthdays.
Next Post
Late Fee Shmate Fee
Previous Post
Lighting the Egg Photograph

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!