Recipe 23.2. Creating a Temporary File

23.2.1. Problem

You need a file to temporarily hold some data.

23.2.2. Solution

Use tmpfile( ) , as in Example 23-10, if the file needs to last only the duration of the running script.

Creating a temporary file with tmpfile( )

<?php $temp_fh = tmpfile(); // write some data to the temp file fputs($temp_fh,"The current time is ".strftime('%c')); // the file goes away when the script ends exit(1); ?>

If the file needs to last longer, generate a filename with tempnam( ), and then use fopen( ), as in Example 23-11.

Creating a temporary file with tempnam( )

<?php $tempfilename = tempnam('/tmp','data-'); $temp_fh = fopen($tempfilename,'w') or die($php_errormsg); fputs($temp_fh,"The current time is ".strftime('%c')); fclose($temp_fh) or die($php_errormsg); ?>

23.2.3. Discussion

The tmpfile( ) function creates a file with a unique name and returns a filehandle. The file is removed when fclose( ) is called on that file handle, or the script ends.

Alternatively, tempnam( ) generates a filename. It takes two arguments: the first is a directory, and the second is a prefix for the filename. If the directory doesn't exist or isn't writable, tempnam( ) uses the system temporary directory'the TMPDIR environment variable in Unix or the TMP environment variable in Windows. Example 7-27 shows what tempnam( ) generates.

Generating a filename with tempnam( )

<?php $tempfilename = tempnam('/tmp','data-'); print "Temporary data will be stored in $tempfilename"; ?>

Example 7-27 prints:

Temporary data will be stored in /tmp/data-GawVoL 

Because of the way PHP generates temporary filenames, a file with the filename that tempnam( ) returns is actually created but left empty, even if your script never explicitly opens the file. This ensures another program won't create a file with the same name between the time that you call tempnam( ) and the time you call fopen( ) with the filename.

23.2.4. See Also

Documentation on tmpfile( ) at and on tempnam( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: