home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePHP CookbookSearch this book

5.8. Encapsulating Complex Data Types as a String

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

Serialized data going into a database always needs to have addslashes( ) called on it (or another database-appropriate escaping method) to ensure it's saved properly.

5.8.4. See Also

Recipe 10.8 for information on escaping data for a database.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.