tags:

views:

1193

answers:

3

I need to convert some files to PDF and then attach them to an email. I'm using Pear Mail for the email side of it and that's fine (mostly--still working out some issues) but as part of this I need to create temporary files. Now I could use the tempnam() function but it sounds like it creates a file on the filesystem, which isn't what I want.

I just want a name in the temporary file system (using sys_get_temp_dir()) that won't clash with someone else running the same script of the same user invoking the script more than once.

Suggestions?

+7  A: 

I've used uniqid() in the past to generate a unique filename, but not actually create the file.

$filename = uniqid(rand(), true) . '.pdf';

The first parameter can be anything you want, but I used rand() here to make it even a bit more random. Using a set prefix, you could further avoid collisions with other temp files in the system.

$filename = uniqid('MyApp', true) . '.pdf';

From there, you just create the file. If all else fails, put it in a while loop and keep generating it until you get one that works.

while (true) {
 $filename = uniqid('MyApp', true) . '.pdf';
 if (!file_exists(sys_get_temp_dir() . $filename)) break;
}
Lusid
+1  A: 

Consider using an uuid for the filename. Consider the uniqid function. http://php.net/uniqid

Michael MacDonald
+1  A: 

You could use part of the date and time in order to create a unique file name, that way it isn't duplicated when invoked more than once.

barfoon