Uploading and deleting unused images 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')
       -&gt;condition('uid', $state['user_id'], '=')
       -&gt;fields('u', array('picture'))
       -&gt;execute()
       -&gt;fetchAssoc();

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

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

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

     $img-&gt;status = FILE_STATUS_PERMANENT;
     $acc-&gt;picture = $img;
     file_save($img);

   }

 } else {
   $acc-&gt;picture = NULL;
 }

 user_save($acc);


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.