Ed9c50a6db8b5e078b5ef84306a8477c

Create a file name from the given prefix and suffix, incorporating an incremented number to ensure that the file doesn't already exist.

<?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 !

A8d3f35baafdaea851914b17dae9e1fc

Adam

October 23, 2008, October 23, 2008 15:18, permalink

1 rating. Login to rate!

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));
    }
?>
151e36cc7f789a4790c8ca437e3a1f60

Chris Dean

October 28, 2008, October 28, 2008 07:48, permalink

4 ratings. Login to rate!

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();
}
?>

Your refactoring





Format Copy from initial code

or Cancel