I would like to have a script that runs on cron, to delete all files that are not currently being used. I noticed that the file_usage table and the hard drive are getting filed with them.
Is there a way to do so?
Drupal should be taking care of this for you. The pattern that modules should be following is:
So unless you've got a buggy module there probably aren't to many unused files sitting around but if you wanted to check it you could run the following query:
select fm.* from file_managed fm
left join file_usage fu on fm.fid = fu.fid
where fu.fid is null
I ran that on a test site and noticed that the devel_generate module isn't properly registering usage of the user's pictures when it creates them. You might notice similar things.
I don't think this is a very good idea. What guarantees you that because the file is currently not being used it will not be used in the future? Also, there are many reasonably priced hosts that offer unlimited hard drive space for like $10 dollars a month so hard drive space would be the least of your concerns. You could consider migrating your site to one of those.
Something that may help 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.
- 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.