5.8.1 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.
5.8.2 Solution
$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);
$new_pantry = unserialize(join('',file('/tmp/pantry')));
5.8.3 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 on $new_cart = unserialize($cart); // if magic_quotes_gpc is off
If magic_quotes_runtime is on, serialized
data stored in a file must be processed with addslashes( ) when writing and stripslashes() when reading:
$fp = fopen('/tmp/cart,'w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);
// if magic_quotes_runtime is on
$new_cart = unserialize(stripslashes(join('',file('/tmp/cart'))));
// if magic_quotes_runtime is off
$new_cart = unserialize(join('',file('/tmp/cart')));
Serialized data read from a database must also be processed
with stripslashes( ) when magic_quotes_runtime is on:
mysql_query(
"INSERT INTO cart (id,data) VALUES (1,'".addslashes(serialize($cart))."')");
$r = mysql_query('SELECT data FROM cart WHERE id = 1');
$ob = mysql_fetch_object($r);
// if magic_quotes_runtime is on
$new_cart = unserialize(stripslashes($ob->data));
// if magic_quotes_runtime is off
$new_cart = unserialize($ob->data);