TechniqueCreate 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; ?> CommentsThe 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. |