Definition

file_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME)
drupal/includes/file.inc, line 382

Description

Copy 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.
  • Checks that $source is not equal to $destination; if they are an error is reported.
  • If file already exists in $destination either the call will error out, replace the file or rename the file based on the $replace parameter.
  • 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 about temporary files.

@see file_unmanaged_copy() @see hook_file_copy()

Parameters

$source A file object.

$destination A string containing the directory $source should be copied to. If this value is omitted, Drupal's 'files' directory will be used.

$replace Replace behavior when the destination file already exists:

  • FILE_EXISTS_REPLACE - Replace the existing file.
  • FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique.
  • FILE_EXISTS_ERROR - Do nothing and return FALSE.

Return value

File object if the copy is successful, or FALSE in the event of an error.

Related topics

Namesort iconDescription
File interfaceCommon file handling functions.

Code

function file_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $source = (object)$source;

  if ($filepath = file_unmanaged_copy($source->filepath, $destination, $replace)) {
    $file = clone $source;
    $file->fid      = NULL;
    $file->filename = basename($filepath);
    $file->filepath = $filepath;
    if ($file = file_save($file)) {
      // Inform modules that the file has been copied.
      module_invoke_all('file_copy', $file, $source);
      return $file;
    }
  }
  return FALSE;
}