Copies 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().
$source: A file object.
$destination: A string containing the destination that $source should be copied to. This must be a stream wrapper URI.
$replace: Replace behavior when the destination file already exists:
File object if the copy is successful, or FALSE in the event of an error.
function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
if (!file_valid_uri($destination)) {
if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
watchdog('file', 'File %file (%realpath) could not be copied, because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array(
'%file' => $source->uri,
'%realpath' => $realpath,
'%destination' => $destination,
));
}
else {
watchdog('file', 'File %file could not be copied, because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array(
'%file' => $source->uri,
'%destination' => $destination,
));
}
drupal_set_message(t('The specified file %file could not be copied, because the destination is invalid. More information is available in the system log.', array(
'%file' => $source->uri,
)), 'error');
return FALSE;
}
if ($uri = file_unmanaged_copy($source->uri, $destination, $replace)) {
$file = clone $source;
$file->fid = NULL;
$file->uri = $uri;
$file->filename = drupal_basename($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);
$file->fid = $existing->fid;
$file->filename = $existing->filename;
}
}
elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
$file->filename = drupal_basename($destination);
}
$file = file_save($file);
// Inform modules that the file has been copied.
module_invoke_all('file_copy', $file, $source);
return $file;
}
return FALSE;
}