PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 5.8 Encapsulating Complex Data Types as a String

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

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

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.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    5.1 Introduction
    Recipe 5.2 Avoiding==Versus=Confusion
    Recipe 5.3 Establishing a Default Value
    Recipe 5.4 Exchanging Values Without Using Temporary Variables
    Recipe 5.5 Creating a Dynamic Variable Name
    Recipe 5.6 Using Static Variables
    Recipe 5.7 Sharing Variables Between Processes
    Recipe 5.8 Encapsulating Complex Data Types as a String
    Recipe 5.9 Dumping Variable Contents as Strings
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele