6.3 Creating a Temporary File


You want to create a temporary file to store program data.

Technique

Use the tempnam() function, which generates a temporary filename in a specified directory:

 <?php $tmp = tempnam ("/home/designmm/public_html", "foobar"); ?> 

Comments

The tempnam() function always creates a unique file in the directory specified ( /home/designmm/public_html ) and with the prefix specified ( foobar ). After the file is created, the name of the file is returned (in this case, we assign it to $tmp_file_name ). After the script is done, make sure to delete the file using the unlink() function:

 <?php $tmp = tempnam ("C:\", "tmpFile"); $fp = @fopen ($tmp, "w"); if (!$fp) {     die ("Cannot open $tmp"); } fputs ($fp, "Hello World\n"); fputs ($fp, "Another Line in a Temporary File"); @fclose ($fp); $fp = @fopen ($tmp, "r"); if (!$fp) {     die ("Cannot open $tmp"); } while ($line = @fgets ($fp, 1024)) {     print $line; } @fclose ($fp); @unlink ($tmp)     or die ("Cannot delete $tmp"); ?> 

Note that if the file directory is not found, the file will be created in the computer's temporary directory (usually stored in the $TMP environment variable).



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