You are here

function file_copy in Drupal 8

Same name and namespace in other branches
  1. 4 includes/file.inc \file_copy()
  2. 5 includes/file.inc \file_copy()
  3. 6 includes/file.inc \file_copy()
  4. 7 includes/file.inc \file_copy()
  5. 9 core/modules/file/file.module \file_copy()

Copies a file to a new location and adds a file record to the database.

This function should be used when manipulating files that have records stored in the database. This is a powerful function that in many ways performs like an advanced version of copy().

  • Checks if $source and $destination are valid and readable/writable.
  • If file already exists in $destination either the call will error out, replace the file or rename the file based on the $replace parameter.
  • If the $source and $destination are equal, the behavior depends on the $replace parameter. FileSystemInterface::EXISTS_REPLACE will error out. FileSystemInterface::EXISTS_RENAME will rename the file until the $destination is unique.
  • Adds the new file to the files database. If the source file is a temporary file, the resulting file will also be a temporary file. See file_save_upload() for details on temporary files.

Parameters

\Drupal\file\FileInterface $source: A file entity.

string $destination: A string containing the destination that $source should be copied to. This must be a stream wrapper URI.

int $replace: (optional) Replace behavior when the destination file already exists. Possible values include:

Return value

\Drupal\file\FileInterface|false File entity if the copy is successful, or FALSE in the event of an error.

See also

\Drupal\Core\File\FileSystemInterface::copy()

hook_file_copy()

5 calls to file_copy()
CopyTest::testExistingError in core/modules/file/tests/src/Kernel/CopyTest.php
Test that copying over an existing file fails when instructed to do so.
CopyTest::testExistingRename in core/modules/file/tests/src/Kernel/CopyTest.php
Test renaming when copying over a file that already exists.
CopyTest::testExistingReplace in core/modules/file/tests/src/Kernel/CopyTest.php
Test replacement when copying over a file that already exists.
CopyTest::testNormal in core/modules/file/tests/src/Kernel/CopyTest.php
Test file copying in the normal, base case.
FileTokenReplaceTest::testFileTokenReplacement in core/modules/file/tests/src/Functional/FileTokenReplaceTest.php
Creates a file, then tests the tokens generated from it.
5 string references to 'file_copy'
d6_file.yml in core/modules/file/migrations/d6_file.yml
core/modules/file/migrations/d6_file.yml
d6_user_picture_file.yml in core/modules/user/migrations/d6_user_picture_file.yml
core/modules/user/migrations/d6_user_picture_file.yml
d7_file.yml in core/modules/file/migrations/d7_file.yml
core/modules/file/migrations/d7_file.yml
d7_file_private.yml in core/modules/file/migrations/d7_file_private.yml
core/modules/file/migrations/d7_file_private.yml
FileCopyTest::doTransform in core/modules/migrate/tests/src/Kernel/process/FileCopyTest.php
Do an import using the destination.

File

core/modules/file/file.module, line 161
Defines a "managed_file" Form API field and a "file" field for Field module.

Code

function file_copy(FileInterface $source, $destination = NULL, $replace = FileSystemInterface::EXISTS_RENAME) {

  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
  $file_system = \Drupal::service('file_system');

  /** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
  $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
  if (!$stream_wrapper_manager
    ->isValidUri($destination)) {
    if (($realpath = $file_system
      ->realpath($source
      ->getFileUri())) !== FALSE) {
      \Drupal::logger('file')
        ->notice('File %file (%realpath) could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', [
        '%file' => $source
          ->getFileUri(),
        '%realpath' => $realpath,
        '%destination' => $destination,
      ]);
    }
    else {
      \Drupal::logger('file')
        ->notice('File %file could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', [
        '%file' => $source
          ->getFileUri(),
        '%destination' => $destination,
      ]);
    }
    \Drupal::messenger()
      ->addError(t('The specified file %file could not be copied because the destination is invalid. More information is available in the system log.', [
      '%file' => $source
        ->getFileUri(),
    ]));
    return FALSE;
  }
  try {
    $uri = $file_system
      ->copy($source
      ->getFileUri(), $destination, $replace);
    $file = $source
      ->createDuplicate();
    $file
      ->setFileUri($uri);
    $file
      ->setFilename($file_system
      ->basename($uri));

    // If we are replacing an existing file re-use its database record.
    // @todo Do not create a new entity in order to update it. See
    //   https://www.drupal.org/node/2241865.
    if ($replace == FileSystemInterface::EXISTS_REPLACE) {
      $existing_files = \Drupal::entityTypeManager()
        ->getStorage('file')
        ->loadByProperties([
        'uri' => $uri,
      ]);
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing
          ->id();
        $file
          ->setOriginalId($existing
          ->id());
        $file
          ->setFilename($existing
          ->getFilename());
      }
    }
    elseif ($replace == FileSystemInterface::EXISTS_RENAME && is_file($destination)) {
      $file
        ->setFilename($file_system
        ->basename($destination));
    }
    $file
      ->save();

    // Inform modules that the file has been copied.
    \Drupal::moduleHandler()
      ->invokeAll('file_copy', [
      $file,
      $source,
    ]);
    return $file;
  } catch (FileException $e) {
    return FALSE;
  }
}