Fix duplicate file names


Drupal won't allow you to have two files with the same filename in a directory. Depending on how you put the file in the directory, Drupal will either rename it or replace the existing file. But it will allow you to have two or more files with the same filename inside different directories. To find and rename all such files you can use the following code snippet:

function MY_MODULE_fix_duplicate_filenames() {
  $connection = \Drupal::database();
  $query = $connection->query("SELECT filename FROM file_managed GROUP BY filename having count(*) >1;");
  $items = $query->fetchAll();

  /** @var \Drupal\file\FileStorageInterface $file_storage */
  $file_storage = \Drupal::entityTypeManager()->getStorage('file');
  /** @var \Drupal\file\FileRepositoryInterface $file_repository */
  $file_repository = \Drupal::service('file.repository');

  foreach ($items as $item) {
    $files = $file_storage->loadByProperties(['filename' => $item->filename]);

    /** @var \Drupal\file\FileInterface $file */
    foreach ($files as $file) {
      $pathinfo = pathinfo($file->getFilename());
      if (!empty($pathinfo['filename'])) {
        if (file_exists($file->getFileUri())) {
          $filename_suffix = time() . '-' . random_int(100000, 1000000);
          $new_destination = str_replace($pathinfo['filename'], $pathinfo['filename'] . '-' . $filename_suffix, $file->getFileUri());
          $file_repository->move($file, $new_destination);

As you can see, this will append a suffix constructed from a timestamp and a random integer value.

About the Author

Goran Nikolovski is an experienced web and AI developer skilled in Drupal, React, and React Native. He founded this website and enjoys sharing his knowledge.