<?php
function unique_file($prefix, $suffix){
$file = sprintf('%s.%s', $prefix, $suffix);
if (file_exists($file))
do
$file = sprintf('%s.%d.%s', $prefix, ++$i, $suffix);
while (file_exists($file));
return $file;
}
Refactorings
No refactoring yet !
Adam
October 23, 2008, October 23, 2008 15:18, permalink
Creates the file to prevent a race condition.
<?php
function unique_file($prefix, $suffix, $index = -1)
{
$filename = unique_filename_for_index($prefix, $suffix, $index);
if ($file = @fopen($filename, "x+")) {
fclose($file);
return $filename;
} else {
return unique_file($prefix, $suffix, ++$index);
}
}
function unique_filename_for_index($prefix, $suffix, $index)
{
return join(".", $index < 0 ? array($prefix, $suffix) :
array($prefix, $index, $suffix));
}
?>
Chris Dean
October 28, 2008, October 28, 2008 07:48, permalink
If the only reason for the number is to ensure the file doesn't exist why not use a unix timestamp?
For most intents and purposes it will always be unique and it will increment itself.
Also I don't se a need to use sprintf for this...
As a result you can strip out all this checking code and just have:
<?php
function unique_file($prefix, $suffix)
{
return $prefix.$suffix.time();
}
?>
Create a file name from the given prefix and suffix, incorporating an incremented number to ensure that the file doesn't already exist.