file_create_filename

file_create_filename($basename, $directory)

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.

Related topics

File interface
Common file handling functions.

File

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

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function file_create_filename($basename, $directory) {
  // 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 (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;
}
doc_Drupal
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.