I have a custom form with manage file input where users can upload their profile images. Upload looks like this:

 $acc = user_load($state['user_id'], TRUE);

 // upload profile image
 if ($state['values']['image'] != '0') {

   //check if this file is already in use, if not, save new file
   $res = db_select('users', 'u')
       ->condition('uid', $state['user_id'], '=')
       ->fields('u', array('picture'))

   if ($res['picture'] != $state['values']['image']) {

     $img = file_load($state['values']['image']);

     file_usage_add($img, 'user', 'user', $state['user_id']);

     $img->status = FILE_STATUS_PERMANENT;
     $acc->picture = $img;


 } else {
   $acc->picture = NULL;


This approach is piling up unused files if user's change their images multiple times. It is because of file_usage_add function that is logging files in database, therefore drupal won't delete files that are logged in file_managed database.

I think I could manually change old file status in database before new log is inserted by file_usage_add and let Drupal automatically remove this unused file. Is this statement right?

Even if it is true, I have strong feeling this is not optimal Drupal way of managing files. Is there a better way?


You can achieve your requirement by using Audit Files module.

Audit files is designed to perform audits of your upload directory and the corresponding database records. It will cross check that all files in the database have a corresponding physical file, or it will check that all files in the upload directory have a corresponding entry in the database.

  • Thx, but this won't solve my problem. Files in database do have a corresponding physical file and all files in the upload directory do have a corresponding entry in the database – Incredible Jan 26 '16 at 13:21
  • 1
    They'll be deleted on a cron job though, unless you've marked them as FILE_STATUS_PERMANENT. Make sure that doesn't happen until a form submission, rather than validation, and you shouldn't have any problems. Same with file usage - don't update that until you're positive the file should be kept. That's how core image fields work and they don't have this issue – Clive Jan 26 '16 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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