Saves a file to the specified destination and creates a database entry.
$data: A string containing the contents of the file.
$destination: A string containing the destination URI. This must be a stream wrapper URI. If no value is provided, a randomized name will be generated and the file will be saved using Drupal's default files scheme, usually "public://".
$replace: Replace behavior when the destination file already exists:
Drupal\file\File A file entity, or FALSE on error.
function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
global $user;
if (empty($destination)) {
$destination = file_default_scheme() . '://';
}
if (!file_valid_uri($destination)) {
watchdog('file', 'The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', array(
'%destination' => $destination,
));
drupal_set_message(t('The data could not be saved because the destination is invalid. More information is available in the system log.'), 'error');
return FALSE;
}
if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {
// Create a file entity.
$file = entity_create('file', array(
'uri' => $uri,
'uid' => $user->uid,
'status' => FILE_STATUS_PERMANENT,
));
// If we are replacing an existing file re-use its database record.
if ($replace == FILE_EXISTS_REPLACE) {
$existing_files = entity_load_multiple_by_properties('file', 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
->save();
return $file;
}
return FALSE;
}