An additional function to file.inc would be nice. This could then be tied into other procedures that allow users to create directories.

<?php
function file_check_directories($path, $mode = 0, $form_item = NULL, $temp = FALSE) {
  $dirs = array(($temp) ? file_directory_temp() : file_directory_path());
  foreach(array_filter(explode('/', trim($path, '/'))) as $dir) {
    $dir = trim($dir);
    if ($dir == '..' || $dir == '.') {
      continue;
    }
    $dirs[] = $dir;
    $path = file_create_path($directory . implode($dirs,'/'));
    $result = file_check_directory($path, $mode, $form_item);
    if(!$result) {
      return FALSE;
    }
  }
  return TRUE;
}
?>

I've seen similar code in a number of modules, and a number of modules fail, including the creation of the temp/file directories within Drupal, when you specify more than one directory to create at a time.

Regards

Alan

Comments

awolfey’s picture

Thanks for this. +1 for adding to file.inc.

eliosh’s picture

Corrected version.

On line $path = file_create_path($directory . implode($dirs,'/')); $directory is not used.


function file_check_directories($path, $mode = 0, $form_item = NULL, $temp = FALSE) {
  $dirs = array(($temp) ? file_directory_temp() : file_directory_path());
  foreach(array_filter(explode('/', trim($path, '/'))) as $dir) {
    $dir = trim($dir);
    if ($dir == '..' || $dir == '.') {
      continue;
    }
    $dirs[] = $dir;
    $path = file_create_path(implode($dirs,'/'));
    $result = file_check_directory($path, $mode, $form_item);
    if(!$result) {
      return FALSE;
    }
  }
  return TRUE;
}

joachim’s picture

+1

At the moment, any module that lets admins specify where to put things has to reimplement its own version of this sort of thing (see in CCK for example) to account for an admin entering a path like my/path/to/files/with/subfolders/that/dont/exist/yet.

Though why not just make file_create_path and file_check_directory able to handle whatever is thrown at them?

alan d.’s picture

Version: 6.x-dev » 7.x-dev
Status: Active » Closed (duplicate)