function FileSystem::createFilename

Same name in other branches
  1. 8.9.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::createFilename()
  2. 10 core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::createFilename()
  3. 11.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::createFilename()

Overrides FileSystemInterface::createFilename

1 call to FileSystem::createFilename()
FileSystem::getDestinationFilename in core/lib/Drupal/Core/File/FileSystem.php
Determines the destination path for a file.

File

core/lib/Drupal/Core/File/FileSystem.php, line 581

Class

FileSystem
Provides helpers to operate on files and stream wrappers.

Namespace

Drupal\Core\File

Code

public function createFilename($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 FileException(sprintf("Invalid filename '%s'", $original));
    }
    if (substr(PHP_OS, 0, 3) == 'WIN') {
        // These characters are not allowed in Windows filenames.
        $basename = str_replace([
            ':',
            '*',
            '?',
            '"',
            '<',
            '>',
            '|',
        ], '_', $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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.