Drupal 7 uploaded image disappears each day

I was recently doing some development in Drupal 7 where I created a custom block that had an image upload field. The image was processed and it was desaturated, brightened and saved. A problem that came up was that every morning when I came in to work on the site, the image was gone. The actual file was missing from the server.

I figured it must be happening when Drupal ran a cron job for it to happen so regularly. After a bit of reading on the Drupal forums as well as Stackoverflow I found this page that describes the file object in depth. I found out that images I had uploaded only had a status flag of 0, which means the file is temporary and removed when the cron is run. I was able to fix the issue by adding this bit of code in to update the status of the image file to 1.

$imageFile = file_load($edit['block_image_nam']);
$imageFile->status = 1; // set to 1 so that it does not get deleted in cleanup
file_save($imageFile);

A pretty simple fix to an annoying problem. Good to know Drupal does some file cleanup and hope it comes in handy for someone else!

4 thoughts on “Drupal 7 uploaded image disappears each day”

  1. I really appreciate the post here – would you mind sharing a exact file and location for this update to be added? I tried couple of places but this crashed the site. I will appreciate it. Thank you!

    1. Hey Marionelli,
      This was custom code for a client, it would most likely be easier if you posted the code you are having trouble with for me to check out. The end goal is to toggle that status flag to 1, otherwise the cron job will remove the file when it runs.

      Levi

Leave a Reply

Your email address will not be published. Required fields are marked *