W3cubDocs

/Drupal 8

function file_unmanaged_copy

file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME)

Copies a file to a new location without database changes or hook invocation.

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. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME will rename the file until the $destination is unique.
  • Works around a PHP bug where copy() does not properly support streams if safe_mode or open_basedir are enabled.

Parameters

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

$destination: A URI containing the destination that $source should be copied to. The URI may be a bare filepath (without a scheme). If this value is omitted, Drupal's default files scheme will be used, usually "public://".

$replace: Replace behavior when the destination file already exists:

Return value

The path to the new file, or FALSE in the event of an error.

See also

https://bugs.php.net/bug.php?id=60456

file_copy()

Related topics

File interface
Common file handling functions.

File

core/includes/file.inc, line 447
API for handling file uploads and server file management.

Code

function file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  if (!file_unmanaged_prepare($source, $destination, $replace)) {
    return FALSE;
  }
  // Attempt to resolve the URIs. This is necessary in certain configurations
  // (see above).
  $real_source = drupal_realpath($source) ? : $source;
  $real_destination = drupal_realpath($destination) ? : $destination;
  // Perform the copy operation.
  if (!@copy($real_source, $real_destination)) {
    \Drupal::logger('file')->error('The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination));
    return FALSE;
  }
  // Set the permissions on the new file.
  drupal_chmod($destination);
  return $destination;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!includes!file.inc/function/file_unmanaged_copy/8.1.x