Create a file with a unique name with PHP

Posted in PHP -

The PHP function tempnam() creates a file with a unique name. This can be useful if you need to output some data into a temporary file for one reason or another, and the actual name of the file is not important. The most simple usage of tempnam() is as follows:

$filename = tempnam('', '');

This will create a zero length filename in the system's temporary directory and return the name generated to $filename. An example of the value returned is as follows:

/tmp/Z8w9c6

Creating a temporary file in a specific location

You can specify the location the file should be created by setting the first parameter. If it's left blank (as in the first example above), does not exist, or is a directory the process does not have write access to, then the system temporary directory will be used instead.

$filename = tempnam('/tmp/test', '');
echo $filename; // outputs e.g. /tmp/test/fA6u4e

The above example specifies /tmp/test as the output directory. This directory must be writable by the process to create a file there. For example, if running under the Apache web server, then the user Apache runs as must have write access to the /tmp/test directory.

Adding a prefix to the temporary filename

Finally, the second parameter allows you to specify a prefix that will be the first part of the filename, as show in the example below:

$filename = tempnam('/tmp/test', 'myprefix-');
echo $filename; // outputs e.g. /tmp/test/myprefix-fA6u4e

Using the temporary file

Calling the tempnam() function creates the file as a zero length file, and the PHP script does not actually delete it when the process completes running. To use the file, use the regular fopen() etc functions and then delete the file when you have finished, eg:

$filename = tempnam('', '');
$fp = fopen($filename, 'w');
...
fclose($fp);
...
unlink($filename);

Summary

In summary, the tempnam() function allows you to create a temporary file in PHP with a unique name which you can then use with the regular file functions, and which you then need to remove yourself at the end of your script if you need it deleted afterwards.



Related posts:


Comments