5.7. Encapsulating Complex Data Types as a String

Problem

You want a string representation of an array or object for storage in a file or database. This string should be easily reconstitutable into the original array or object.

Solution

Use serialize( ) to encode variables and their values into a textual form:

$pantry = array('sugar' => '2 lbs.','butter' => '3 sticks');
$fp = fopen('/tmp/pantry','w') or die ("Can't open pantry");
fputs($fp,serialize($pantry));
fclose($fp);

To recreate the variables, use unserialize( ) :

$new_pantry = unserialize(join('',file('/tmp/pantry')));

Discussion

The serialized string that is reconstituted into $pantry looks like:

a:2:{s:5:"sugar";s:6:"2 lbs.";s:6:"butter";s:8:"3 sticks";}

This stores enough information to bring back all the values in the array, but the variable name itself isn’t stored in the serialized representation.

When passing serialized data from page to page in a URL, call urlencode( ) on the data to make sure URL metacharacters are escaped in it:

$shopping_cart = array('Poppy Seed Bagel' => 2,
                       'Plain Bagel' => 1,
                       'Lox' => 4);
print '<a href="next.php?cart='.urlencode(serialize($shopping_cart)).'">Next</a>';

The magic_quotes_gpc and magic_quotes_runtime configuration settings affect data being passed to unserialize( ). If magic_quotes_gpc is on, data passed in URLs, POST variables, or cookies must be processed with stripslashes( ) before it’s unserialized:

$new_cart = unserialize(stripslashes($cart)); // if magic_quotes_gpc is ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.