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'))
->execute()
->fetchAssoc();
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;
file_save($img);
}
} else {
$acc->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?