W3cubDocs

/Drupal 8

function file_save_htaccess

file_save_htaccess($directory, $private = TRUE, $force_overwrite = FALSE)

Creates a .htaccess file in the given directory.

Parameters

string $directory: The directory.

bool $private: (Optional) FALSE indicates that $directory should be a web-accessible directory. Defaults to TRUE which indicates a private directory.

bool $force_overwrite: (Optional) Set to TRUE to attempt to overwrite the existing .htaccess file if one is already present. Defaults to FALSE.

Related topics

File interface
Common file handling functions.

File

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

Code

function file_save_htaccess($directory, $private = TRUE, $force_overwrite = FALSE) {
  if (\Drupal::service('file_system')->uriScheme($directory)) {
    $htaccess_path = file_stream_wrapper_uri_normalize($directory . '/.htaccess');
  }
  else {
    $directory = rtrim($directory, '/\\');
    $htaccess_path = $directory . '/.htaccess';
  }

  if (file_exists($htaccess_path) && !$force_overwrite) {
    // Short circuit if the .htaccess file already exists.
    return TRUE;
  }
  $htaccess_lines = FileStorage::htaccessLines($private);

  // Write the .htaccess file.
  if (file_exists($directory) && is_writable($directory) && file_put_contents($htaccess_path, $htaccess_lines)) {
    return drupal_chmod($htaccess_path, 0444);
  }
  else {
    $variables = array('%directory' => $directory, '@htaccess' => $htaccess_lines);
    \Drupal::logger('security')->error("Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <pre><code>@htaccess</code></pre>", $variables);
    return FALSE;
  }
}

© 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_save_htaccess/8.1.x