file_create_filename

Definition

file_create_filename($basename, $directory)
drupal/includes/file.inc, line 656

Description

Create a full file path from a directory and filename.

If a file with the specified name already exists, an alternative will be used.

Parameters

$basename String filename

$directory String directory

Return value

File path consisting of $directory and a unique filename based off of $basename.

Related topics

Namesort iconDescription
File interfaceCommon file handling functions.

Code

function file_create_filename($basename, $directory) {
  $destination = $directory . '/' . $basename;

  if (file_exists($destination)) {
    // Destination file already exists, generate an alternative.
    $pos = strrpos($basename, '.');
    if ($pos !== FALSE) {
      $name = substr($basename, 0, $pos);
      $ext = substr($basename, $pos);
    }
    else {
      $name = $basename;
      $ext = '';
    }

    $counter = 0;
    do {
      $destination = $directory . '/' . $name . '_' . $counter++ . $ext;
    } while (file_exists($destination));
  }

  return $destination;
}