Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. FileSystemInterface.php

function FileSystemInterface::copy

Copies a file to a new location without invoking the file API.

This is a powerful function that in many ways performs like an advanced version of copy().

  • If $source and $destination are valid and readable/writable, then only perform the copy operation.
  • If $source and $destination are equal then a FileException exception is thrown.
  • If the $destination file already exists, the behavior depends on the $fileExists parameter as follows `FileExists::Error` will error out, `FileExists::Replace` will replace the existing file, and `FileExists::Rename` will assign a new unique name.
  • Provides a fallback using realpaths if the move fails using stream wrappers. This can occur because PHP's copy() function does not properly support streams if open_basedir is enabled.

Example:


use Drupal\Core\File\FileExists;
use Drupal\Core\File\FileSystemInterface;
...
$directory = 'public://example-dir';
$file_system = \Drupal::service('file_system');
$file_system->copy($filepath, $directory . '/' . basename($filepath), FileExists::Replace);

In this example, file is copied from $filepath and is replaced at the destination if exists.

Parameters

string $source: A string specifying the filepath or URI of the source file.

string $destination: A URI containing the destination that $source should be copied to. The URI may be a bare filepath (without a scheme).

\Drupal\Core\File\FileExists|int $fileExists: The behavior when the destination file already exists.

Return value

string The path to the new file.

Throws

\Drupal\Core\File\Exception\FileException Implementation may throw FileException or its subtype on failure.

\ValueError Thrown if $fileExists is a legacy int and not a valid value.

1 method overrides FileSystemInterface::copy()
FileSystem::copy in core/lib/Drupal/Core/File/FileSystem.php
Copies a file to a new location without invoking the file API.

File

core/lib/Drupal/Core/File/FileSystemInterface.php, line 309

Class

FileSystemInterface
Provides an interface for helpers that operate on files and stream wrappers.

Namespace

Drupal\Core\File

Code

public function copy($source, $destination, $fileExists = FileExists::Rename);

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal