Is there a way to delete files/images from the server automatically when the main node is deleted?

How do I implement this?

2 Answers 2


It's a revisions thing. I guess it makes sense. If you have revisions enabled for that content type, it keeps all your old files on the server (associated with old revisions), so replacing a file definitely is harder. If you try to remove it and add it again to the node, the name/link is updated, as I mentioned in my question. Since a file with that name is kept on the server and there is a name duplication, it adds those "_0", "_1" etc suffixes to future uploaded versions of that file's name.

I understand why this is happening though, since the whole point of revisioning is being able to revert to any past version of the page.

The work-around is that you can actually delete the old revision from the 'Revision' or 'Moderate' tab (if using Workbench Moderation) that contained the file you're trying to replace. Then upload it again, and the name should then match without you having to go back and edit any links pointing to that file.

Hope that makes sense and that it helps somebody else too!

  • 1
    If a node is deleted, as the OP is saying, also the revisions are deleted. It's not a matter of old revisions.
    – apaderno
    Apr 4, 2016 at 9:25

When a node is deleted. the images and other files uploaded in the node edit form are automatically deleted during cron tasks; the files are deleted if they have been uploaded more than 6 hours ago.

If, for any reason, you need to delete them faster, and before 6 hours are passed, you could use the following code. Put it in a file (e.g. delete-files.php) in the directory where Drupal is installed (which is the same directory where you find the cron.php file).

   * Root directory of Drupal installation.
  define('DRUPAL_ROOT', getcwd());

  include_once DRUPAL_ROOT . '/includes/bootstrap.inc';

  // Delete 100 files at time.
  $result = db_query_range('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - 60 * 60  
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {
      $references = file_usage_list($file);
      if (empty($references)) {

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.