10.10 Serialization


You want to save variable contents as a string.

Technique

Create functions that implement the serialize() and unserialize() functions, and then read and write data to a file:

 <?php // // File: loadsave.inc //   Library functions for saving and //   loading data to and from a file. // // // int save (string varname): //   Save the value of varname to file. // function save($var) {     global $$var;     $data = serialize($$var); // String Rep. of $$var     $filename = "php_serialized_vars/" . $$var . ".txt";     $fp = @fopen($filename, "w")             or die("Cannot open $filename for write access");     fwrite($fp, $data);     @fclose($fp)       or die("Cannot close $filename");     return(true); } // // int load (string varname) //   Load the value of varname from a file. // function load($var) {     global $$var; // Put the saved variable in the global                   // namespace     $filename = "php_serialized_vars/" . $$var . ".txt";     $fp = @fopen($filename, "r")             or die("Cannot open $filename for read access");     $data = fread($fp, filesize($filename));     @fclose($fp)        or die("Cannot close $filename");     $$var = unserialize($data);     return(true); } ?> 

Then you can call these newly created functions, like this:

save.php:

 <?php $foo = "hello"; save('foo'); ?> <a href="load.php">Click here</a> 

load.php:

 <?php load('foo'); print $foo; ?> 

Comments

The serialize() function creates a string representation of PHP data, whether that data is an array, object, plain string, or number. The unserialize() function will read this string and bring back the original data, much like a compression and decompression program such as bzip or gzip. Note that when unserializing an object, you need to have the object's class definition loaded first, just as for sessions.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net