n Permanently delete unused/orphaned files in drupal 8  | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Code snippet that can be used to permanently delete unused/orphaned files in drupal 8.

 * override hook_cron()
function mymodule_cron()
  // get all files ids
  $fids = Drupal::entityQuery('file')->execute();
  $file_usage = Drupal::service('file.usage');
  // loop all fids and load files by fid
  foreach ($fids as $fid) {
    $file = Drupal\file\Entity\File::load($fid);
    $usage = $file_usage->listUsage($file);
    // check if file not used
    if (count($usage) == 0) {

to excute this code just run your cron and check your files at "/admin/content/files".

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook