Skip to content

Instantly share code, notes, and snippets.

@DuaelFr
Last active August 5, 2021 06:12
Show Gist options
  • Save DuaelFr/6450482 to your computer and use it in GitHub Desktop.
Save DuaelFr/6450482 to your computer and use it in GitHub Desktop.
Download a distant file and save it as a local managed file with drupal.
<?php
/**
* Download a file to the destination and save it into drupal managed files.
*
* @param String $url
* The file to download URL.
* @param String $destination
* The path where the file will be stored. Can be a drupal stream like
* "public://my_dowloads" for example.
* @param array $existing
* (optionnal) A managed file used to compare with the new downloaded file
* and avoid to keep the same file twice. If the downloaded file have the same
* filename than the managed one, the downloaded file will replace the managed
* one if they are different.
*
* @return array
* The managed file.
* @throws MyModuleException
*/
function _MYMODULE_handle_file($url, $destination, $existing = NULL) {
if (!file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
throw new MyModuleException('Cannot prepare directory ' . $destination);
}
// Download file content.
$data = @file_get_contents($url);
if (empty($data)) {
throw new MyModuleException('Cannot download the file ' . $url);
}
if (!empty($existing)) {
$old_file = $existing['uri'];
// If new file different from old one, replace it.
if (md5_file($old_file) != md5($data) && file_unmanaged_save_data($data, $old_file, FILE_EXISTS_REPLACE)) {
$existing['filemime'] = file_get_mimetype($existing['uri']);
$file = file_save((object) $existing);
}
else {
$file = (object) $existing;
}
}
else {
$filename = preg_replace('#^.*://[^/]*/(.*)$#', '$1', $url);
$filename = str_replace('/', '-', $filename);
if (module_exists('transliteration')) {
$filename = transliteration_clean_filename($filename);
}
$file = file_save_data($data, $destination . '/' . $filename, FILE_EXISTS_RENAME);
}
// Save and return file.
if (empty($file)) {
throw new MyModuleException('Cannot save the file ' . $url);
}
$file->display = 1; // Fix issue with wrapper.
return (array) $file;
}
class MyModuleException extends Exception {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment