I've just started using file lock to prevent images getting deleted, so we can build up a store of images for use at a later date. I think this module will solve a problem I've had, but only for images uploaded from this point forward.

How can I also apply this protection retrospectively to:

  1. Images already in file fields

  2. Images uploaded by FTP (well, you know, SFTP )

1 Answer 1


To add a file_lock usage record for all existing files without one:

INSERT INTO file_usage (fid, module, `type`, id, `count`)
SELECT fid, 'file_lock' module, 'module' `type`, 0 id, 1 `count`
FROM file_managed 
  SELECT id FROM file_usage
  WHERE file_managed.fid = file_usage.fid
        AND `type`='module'
        AND id=0
        AND `module` = 'file_lock'
        AND `count`>0

To add a file_lock record for all files in a directory that are NOT registered in the file_managed table

Here I loop through all likely image files in and write them as public:// file_managed records if none exists.

  • preg_ls is not PHP/Drupal core - nicked it from PHP comment - v useful!

  • I exclude the styles/ directory which stores the variants made by different image styles. I also exclude the images/backup/ directory - this is particular to my needs, but I left the code in as you'll likely have something to exclude too.

  • This assumes you have no private:// files and that everything under sites/default/files is to be a public:// file. do not run this as it is if you use private files at all!

  • It also assumes that on file_save, file_lock will add its own lock (based on your config for file_lock).

And now the code:

$dir = DRUPAL_ROOT . "/sites/default/files/";
foreach (preg_ls($dir, true, '/\.(jpe?g|gif|png|bmp)$/i') as $_) {

  $_ = substr($_, strlen($dir));
  if (preg_match('@^(styles/|images/backup/)@', $_)) {

  $uri = "public://$_";
  if (!db_query("SELECT fid FROM {file_managed} WHERE uri = :uri",[':uri' => $uri])->rowCount()) {
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid = $user->uid;
    $file->status = FILE_STATUS_PERMANENT;

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.