You are here

function file_create_filename in Drupal 7

Same name and namespace in other branches
  1. 8 core/includes/file.inc \file_create_filename()
  2. 4 includes/file.inc \file_create_filename()
  3. 5 includes/file.inc \file_create_filename()
  4. 6 includes/file.inc \file_create_filename()

Creates 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 containing the directory or parent URI.

Return value

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

Throws

RuntimeException Thrown if the $basename is not valid UTF-8 or another error occurs stripping control characters.

Related topics

3 calls to file_create_filename()
FileDirectoryTest::testFileCreateNewFilepath in modules/simpletest/tests/file.test
This will take a directory and path, and find a valid filepath that is not taken by another file.
FileDownloadTest::checkUrl in modules/simpletest/tests/file.test
Download a file from the URL generated by file_create_url().
file_destination in includes/file.inc
Determines the destination path for a file.

File

includes/file.inc, line 1240
API for handling file uploads and server file management.

Code

function file_create_filename($basename, $directory) {
  $original = $basename;

  // Strip control characters (ASCII value < 32). Though these are allowed in
  // some filesystems, not many applications handle them well.
  $basename = preg_replace('/[\\x00-\\x1F]/u', '_', $basename);
  if (preg_last_error() !== PREG_NO_ERROR) {
    throw new RuntimeException(sprintf("Invalid filename '%s'", $original));
  }
  if (substr(PHP_OS, 0, 3) == 'WIN') {

    // These characters are not allowed in Windows filenames
    $basename = str_replace(array(
      ':',
      '*',
      '?',
      '"',
      '<',
      '>',
      '|',
    ), '_', $basename);
  }

  // A URI or path may already have a trailing slash or look like "public://".
  if (substr($directory, -1) == '/') {
    $separator = '';
  }
  else {
    $separator = '/';
  }
  $destination = $directory . $separator . $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 . $separator . $name . '_' . $counter++ . $ext;
    } while (file_exists($destination));
  }
  return $destination;
}