Unique Temporary File Names With PHP

By | May 26, 2008

When you work with multiple threads in PHP, you often need to use temporary files. When you have a few files, everything goes well. But when the number of threads is quite big and you need to store your data in temporary files, you may get stuck at this point. A PHP function will save your time by creating random names with mt_rand, md5 and any other functions and word combination. tempnam allows you to create files in the given directory with unique names. You don’t have to worry that the file may exist – file names are absolutely unique and this is guaranteed by PHP :). Please, note that files created by this function are not automatically deleted and you need to have the code that allows to destroy them.

Please, also note that this function output depends on PHP version you use. Starting from 5.2.4 tempnam will return an absolute path to the file so it is ok to use in file operations, but if you need to have links for html, be careful and check your code.

Hope that usage of this function will save your time.