What is the proper way, through code, to delete images on an entity?

I have a cron function that processes like so:

function processQueuedPropertyPhotoset($entity, $photos) {
if (!is_array($photos)) {
  watchdog('mymodule', 'Trying to process photos for a property but it has no photos. Aborting.');

if (is_array($entity->field_property_image) && count($entity->field_property_image)) {
  foreach ($entity->field_property_image['und'] as $key => $value) {
    $photo = file_load($value['fid']);

    if ($photo) {
      file_delete($photo, TRUE);

// wipe clean the records in the field_ table


// rest of code processes and saves new images

I am curious if this is the proper or effective way. Also, do the image derivatives generated get cleaned out by Drupal this way too? I notice there is a 'deleted' field in the database on the Image field table definition. When is this ever used?

This method cleans the entity data, removes the images from the server and files table. I am simply curious as if is an acceptable method that covers all the bases in Drupal or if there is an API function to simplify this. This function is called daily when we run a third party integration web service.

1 Answer 1


If you want to make sure that the image files are definitely deleted (regardless of whether or not another part of the system has declared a vested interest in that file), what you're doing looks spot on to me.

There's already a function run by core on cron (system_cron() specifically) that deletes files marked as FILE_STATUS_TEMPORARY in the file_managed table, but that function consults the file_usage table and doesn't delete if the file is reported as being in use (which it will be if the field values haven't been removed from the entity yet).

Passing TRUE as the second parameter to file_delete() like you're currently doing is the cleanest way to force the deletion (any records in file_usage are also cleaned up so there's no stale data).

The image derivatives will be deleted automatically, as the image module implements hook_file_delete() and flushes the image cache for the file URI (see image_file_delete()).

The deleted column in the field tables is just there to mark the fields for deletion at a later date (I imagine so the subsequent page load isn't affected if there's a lot of data to delete). There are identical columns in the field_config and field_config_instance tables for the same reason.

The field module purges any data marked for deletion in the cron run (field_cron()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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