File managed entire folder Drupal

Some information on managed and unmanaged files in Drupal

If a file is on a certain folder of the webserver within the Drupal folders it does not mean that Drupal knows it!

When Drupal “store” the presence of a certain file (i.e. public://myfile.pdf) it became a managed file.

You can add a file to managed with file_save_data function.

Luckly or unfortunaly a function that manage an entire directory of files, maybe in a recursive way, is not present in Drupal core.

How to import a folder of files to Drupal?

I create a script to this in a clean and easy way.

  $destination = 'public://path-to-folder';
  $regex = '/.*\.jpg$/'; // This will identify jpg files

  $paths = file_scan_directory($destination,$regex);
  foreach($paths as $path => $data){
    $realPath = drupal_realpath($path);
    $handle = fopen($realPath, 'r');
    $file = file_save_data($handle, $path, FILE_EXISTS_REPLACE);

Note that dpm function is provided with a contrib module: Devel.


I have used this functionality to put lots of images in the media library (made with Media module) and make them available for redactors.