| Versions | |
|---|---|
| 4.7 – 6 | file_move(&$source, |
| 7 | file_move(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) |
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.
$source A file object.
$destination A string containing the destination that $source should be moved to. This must be a stream wrapper URI. If this value is omitted, Drupal's default files scheme will be used, usually "public://".
$replace Replace behavior when the destination file already exists:
Resulting file object for success, or FALSE in the event of an error.
drupal/
<?php
function file_move(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
if (!file_valid_uri($destination)) {
watchdog('file', 'File %file (%realpath) could not be moved, because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->uri, '%realpath' => drupal_realpath($source->uri), '%destination' => $destination));
drupal_set_message(t('The specified file %file could not be moved, because the destination is invalid. More information is available in the system log.', array('%file' => $source->uri)), 'error');
return FALSE;
}
if ($uri = file_unmanaged_move($source->uri, $destination, $replace)) {
$delete_source = FALSE;
$file = clone $source;
$file->uri = $uri;
// If we are replacing an existing file re-use its database record.
if ($replace == FILE_EXISTS_REPLACE) {
$existing_files = file_load_multiple(array(), array('uri' => $uri));
if (count($existing_files)) {
$existing = reset($existing_files);
$delete_source = TRUE;
$file->fid = $existing->fid;
}
}
// If we are renaming around an existing file (rather than a directory),
// use its basename for the filename.
elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
$file->filename = basename($destination);
}
$file = file_save($file);
// Inform modules that the file has been moved.
module_invoke_all('file_move', $file, $source);
if ($delete_source) {
// Try a soft delete to remove original if it's not in use elsewhere.
file_delete($source);
}
return $file;
}
return FALSE;
}
?>