Unique and temporary file names in PHP?
PhpPhp Problem Overview
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?
Php Solutions
Solution 1 - Php
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;
}
Solution 2 - Php
Seriously, use tempnam(). Yes, this creates the file, but this is a very intentional security measure designed to prevent another process on your system from "stealing" your filename and causing your process to overwrite files you don't want.
I.e., consider this sequence:
- You generate a random name.
- You check the file system to make sure it doesn't exist. If it does, repeat the previous step.
- Another, evil, process creates a file with the same name as a hard link to a file Mr Evil wants you to accidentally overwrite.
- You open the file, thinking you're creating the file rather than opening an existing one in write mode and you start writing to it.
- You just overwrote something important.
PHP's tempnam() actually calls the system's mkstemp under the hood (that's for Linux... substitute the "best practice" function for other OSs), which goes through a process like this:
- Pick a filename
- Create the file with restrictive permissions, inside a directory that prevents others from removing files it doesn't own (that's what the sticky-bit does on /var/tmp and /tmp)
- Confirms that the file created still has the restrictive permissions.
- If any of the above fails, try again with a different name.
- Returns the filename created.
Now, you can do all of those things yourself, but why, when "the proper function" does everything that's required to create secure temporary files, and that almost always involves creating an empty file for you.
Exceptions:
- You're creating a temporary file in a directory that only your process can create/delete files in.
- Create a randomly generated temporary directory, which only your process can create/delete files in.
Solution 3 - Php
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.
Solution 4 - Php
Better use Unix timestamp with the user id.
$filename='file_'.time().'_'.$id.'.jepg';
Solution 5 - Php
Another alternative based on @Lusid
answer with a failover of max execution time:
// Max exectution time of 10 seconds.
$maxExecTime = time() + 10;
$isUnique = false;
while (time() !== $maxExecTime) {
// Unique file name
$uniqueFileName = uniqid(mt_rand(), true) . '.pdf';
if (!file_exists(sys_get_temp_dir() . $uniqueFileName)){
$isUnique = true;
break;
}
}
if($isUnique){
// Save your file with your unique name
}else{
// Time limit was exceeded without finding a unique name
}
> Note:
>
> I prefer to use mt_rand
instead of rand
because the first function use Mersenne Twister algorithm
and it's faster than the second (LCG
).
More info:
Solution 6 - Php
Consider using an uuid for the filename. Consider the uniqid function. http://php.net/uniqid
Solution 7 - Php
I recomend you to use the PHP function http://www.php.net/tempnam
$file=tempnam('tmpdownload', 'Ergebnis_'.date(Y.m.d).'_').'.pdf';
echo $file;
/var/www/html/tmpdownload/Ergebnis_20071004_Xbn6PY.pdf
<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>
Solution 8 - Php
My idea is to use a recursive function to see if the filename exists, and if it does, iterate to the next integer:
function check_revision($filename, $rev){
$new_filename = $filename."-".$rev.".csv";
if(file_exists($new_filename)){
$new_filename = check_revision($filename, $rev++);
}
return $new_filename;
}
$revision = 1;
$filename = "whatever";
$filename = check_revision($filename, $revision);
Solution 9 - Php
function gen_filename($dir) {
if (!@is_dir($dir)) {
@mkdir($dir, 0777, true);
}
$filename = uniqid('MyApp.', true).".pdf";
if (@is_file($dir."/".$filename)) {
return $this->gen_filename($dir);
}
return $filename;
}
Solution 10 - Php
Update 2020
hash_file('md5', $file_pathname)
This way you will prevent duplications.