Same name and namespace in other branches
  1. 7.x includes/file.inc \file_create_htaccess()

Creates a .htaccess file in the given directory.

Parameters

$directory: The directory.

$form_item: An optional string containing the name of a form item that any errors will be attached to. Useful when called from file_check_directory() to validate a directory path entered as a form value. An error will consequently prevent form submit handlers from running, and instead display the form along with the error messages.

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

Related topics

3 calls to file_create_htaccess()
file_check_directory in includes/file.inc
Checks whether a directory exists and is writable.
install_main in ./install.php
The Drupal installation happens in a series of steps. We begin by verifying that the current environment meets our minimum requirements. We then go on to verify that settings.php is properly configured. From there we connect to the configured database…
system_requirements in modules/system/system.install
Implementation of hook_requirements().

File

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

Code

function file_create_htaccess($directory, $form_item = NULL, $force_overwrite = FALSE) {
  if (!is_file("{$directory}/.htaccess") || $force_overwrite) {
    $htaccess_lines = file_htaccess_lines();
    if (($fp = fopen("{$directory}/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
      fclose($fp);
      chmod($directory . '/.htaccess', 0664);
    }
    else {
      $variables = array(
        '%directory' => $directory,
        '!htaccess' => '<br />' . nl2br(check_plain($htaccess_lines)),
      );
      if ($form_item) {
        form_set_error($form_item, t("Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <code>!htaccess</code>", $variables));
      }
      watchdog('security', "Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <code>!htaccess</code>", $variables, WATCHDOG_ERROR);
    }
  }
}