Definition

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

Description

Move a file to a new location and update the file's database entry.

Moving a file is performed by copying the file to the new location and then deleting the original.

  • Checks if $source and $destination are valid and readable/writable.
  • Performs a file move if $source is not equal to $destination.
  • 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.

@see file_unmanaged_move() @see hook_file_move()

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

Resulting file object for success, or FALSE in the event of an error.

Related topics

Namesort iconDescription
File interfaceCommon file handling functions.

Code

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

  if ($filepath = file_unmanaged_move($source->filepath, $destination, $replace)) {
    $file = clone $source;
    $file->filename = basename($filepath);
    $file->filepath = $filepath;
    if ($file = file_save($file)) {
      // Inform modules that the file has been moved.
      module_invoke_all('file_move', $file, $source);
      return $file;
    }
    drupal_set_message(t('The removal of the original file %file has failed.', array('%file' => $source->filepath)), 'error');
  }
  return FALSE;
}