Drupal - How to find orphaned files and images which are not linked from any css stylesheet or from any node?

You can find orphaned files by running the following MySQL query:

SELECT fm.*
FROM file_managed AS fm
LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
WHERE fu.type = 'node' AND n.nid IS NULL

This returns all files which have no associated node. I'm not sure if it's safe to delete the returned rows and files, probably also depends on your module setup. Only use at your own risk!

Source: http://drupal.org/node/733258#comment-5582764


For those coming to this post three years later, there's a little module you can use to do this called Fancy File Delete.

At the time of this post, it's in beta, so use it at your own risk. As always, cleaning up orphaned anything through DB queries can be sketchy and its success depends heavily on your particular module setup.


Something that may help to identify "files that are no longer attached to nodes or files and directory that are not in the file managed table" (as in the duplicate question about "How to do delete unused files?"), is to use the File Checker module. Some details about it, from its project page:

In a perfect Drupal world your server filesystem and its correspoding entries in Drupal's files table are 100% synchronized. But what if parts of your file system have been corrupted due to some disk failure? Or one of your modules messed up your database and files? Or your deploy script went beserk? Well, then this module will help you to monitor and find out which files are out of sync.

Out of the box the files table has two kind of statuses: Temporary (0) and Permanent (1). The file checker introduces an additional status Missing (2). In scope of the verification process which can be triggered in various ways the status column of the files table is updated.

Features

  • Run verification process: on demand, via cron, via drush (in planning)
  • File list overview page with filters
  • Views integration
  • Drush command for file checking

If you want to export the results of a view it's recommended to use views_data_export module.

So what you could do is like so:

  • Clone (copy) your site to some dev environment, but don't copy any of the files in the directory you want to check. As a variation (if this question is about a non-production status site), just temporary move all files out of that directory.
  • Use the File Checker module to find out what files are "missing": these are the files that are obviously not unused. But any file that this module does not argue about is ... unused!
  • By copying all missing files to the correct location of the directory you want to check, you then step-by-step recreate a perfect content of your directory.

Note: even though this question is about D7, the is an (alfa) version of it also for D8.

Tags:

Files

7