W3cubDocs

/Drupal 8

function file_prepare_directory

file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS)

Checks that the directory exists and is writable.

Directories need to have execute permissions to be considered a directory by FTP servers, etc.

Parameters

$directory: A string reference containing the name of a directory path or URI. A trailing slash will be trimmed from a path.

$options: A bitmask to indicate if the directory should be created if it does not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only (FILE_MODIFY_PERMISSIONS).

Return value

TRUE if the directory exists (or was created) and is writable. FALSE otherwise.

Related topics

File interface
Common file handling functions.

File

core/includes/file.inc, line 284
API for handling file uploads and server file management.

Code

function file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS) {
  if (!file_stream_wrapper_valid_scheme(\Drupal::service('file_system')->uriScheme($directory))) {
    // Only trim if we're not dealing with a stream.
    $directory = rtrim($directory, '/\\');
  }

  // Check if directory exists.
  if (!is_dir($directory)) {
    // Let mkdir() recursively create directories and use the default directory
    // permissions.
    if ($options & FILE_CREATE_DIRECTORY) {
      return @drupal_mkdir($directory, NULL, TRUE);
    }
    return FALSE;
  }
  // The directory exists, so check to see if it is writable.
  $writable = is_writable($directory);
  if (!$writable && ($options & FILE_MODIFY_PERMISSIONS)) {
    return drupal_chmod($directory);
  }

  return $writable;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!includes!file.inc/function/file_prepare_directory/8.1.x