function FileSystem::copy
Same name and namespace in other branches
- 9 core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::copy()
- 8.9.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::copy()
- 11.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::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().
- 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 $fileExists parameter.
- If the $source and $destination are equal, the behavior depends on the $fileExists parameter.
- 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. See https://bugs.php.net/bug.php?id=60456
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.
Overrides FileSystemInterface::copy
File
-
core/
lib/ Drupal/ Core/ File/ FileSystem.php, line 290
Class
- FileSystem
- Provides helpers to operate on files and stream wrappers.
Namespace
Drupal\Core\FileCode
public function copy($source, $destination, $fileExists = FileExists::Rename) {
if (!$fileExists instanceof FileExists) {
// @phpstan-ignore-next-line
$fileExists = FileExists::fromLegacyInt($fileExists, __METHOD__);
}
$this->prepareDestination($source, $destination, $fileExists);
if (!@copy($source, $destination)) {
// If the copy failed and realpaths exist, retry the operation using them
// instead.
$real_source = $this->realpath($source) ?: $source;
$real_destination = $this->realpath($destination) ?: $destination;
if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
throw new FileWriteException("The specified file '{$source}' could not be copied to '{$destination}'.");
}
}
// Set the permissions on the new file.
$this->chmod($destination);
return $destination;
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.