On /admin/config/media/file-system, there is the Delete temporary files after X hours setting.

Does this specifically refer to files in /tmp or in the temporary folder? Does t possibly delete "unused" files?

I ask because I use file_save_data() to save files and I'm worried that Drupal decides to delete some of these files, as they won't be referenced anywhere except in my own custom table.

1 Answer 1


Files uploaded to managed files will be set as temporary. You need to set the file status as permanent, and add a usage, to prevent the file from being deleted.

Setting files as permanent can be done using File::setPermanent(). File usages can be added as follows:

$fid = 1; // The file ID
$file = \Drupal\file\Entity\File::load($fid);
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', $entity_type, $entity_id);

This will add a 'usage' for the file. When deleted, you need to remove the file usage. Files that have been set to permanent, and have a file usage applied, will not be deleted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.