file_copy

Хочешь помочь с переводом? Это очень просто и быстро. Лишь зарегистрируйся, и можешь тут же начать переводить.

includes/file.inc, строка 215

Версии
5 – 6
file_copy(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME)

Копирует файл из одного места в другое. Эта мощная функция работает как расширенная версия функции copy().

  • Проверяет существует ли исходный файл ($source) и папка назначения чтения ($dest), а также проверят есть ли права на чтение исходного файла и запись в папку назначения.
  • Делает проверку того не являются ли одинаковыми $source и $dest.
  • Если файл уже есть в папке назначения ($dest) либо выдает сообщение об ошибке, либо перезаписывает файл, либо переименовывает его, руководствуясь значением параметра $replace.

Параметры

$source — строка содержащая путь к исходному файлу. Имя файла, указанное в этом параметре, будет использоваться как имя скопированного файла.

$dest — строка, содержащая путь к папке, в которую будет скопирован файл $source. Если этот параметр опущен, то будет использоваться стандартная папка files Друпала.

$replace — поведение, в случае если в папке назначения уже есть файл с таким именем.

  • FILE_EXISTS_REPLACE - заменить существущий файл новым
  • FILE_EXISTS_RENAME - добавить суффикс _{incrementing number}
  • FILE_EXISTS_ERROR - ничего не делать, вернуть значение FALSE.

Возвращаемое значение

True в случае удачи, и FALSE при ошибке

Связанные темы

▾ 4 функции вызывают file_copy()

color_scheme_form_submit in modules/color/color.module
Submit handler for color change form.
file_move in includes/file.inc
Перемещает файл в новое место.
system_theme_settings in modules/system/system.admin.inc
Form builder; display theme configuration for entire site and individual themes.
user_validate_picture in modules/user/user.module

Код

<?php
function file_copy(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  $dest = file_create_path($dest);

  $directory = $dest;
  $basename = file_check_path($directory);

  // Make sure we at least have a valid directory.
  if ($basename === FALSE) {
    $source = is_object($source) ? $source->filepath : $source;
    drupal_set_message(t('The selected file %file could not be uploaded, because the destination %directory is not properly configured.', array('%file' => $source, '%directory' => $dest)), 'error');
    watchdog('file system', 'The selected file %file could not be uploaded, because the destination %directory could not be found, or because its permissions do not allow the file to be written.', array('%file' => $source, '%directory' => $dest), WATCHDOG_ERROR);
    return 0;
  }

  // Process a file upload object.
  if (is_object($source)) {
    $file = $source;
    $source = $file->filepath;
    if (!$basename) {
      $basename = $file->filename;
    }
  }

  $source = realpath($source);
  if (!file_exists($source)) {
    drupal_set_message(t('The selected file %file could not be copied, because no file by that name exists. Please check that you supplied the correct filename.', array('%file' => $source)), 'error');
    return 0;
  }

  // If the destination file is not specified then use the filename of the source file.
  $basename = $basename ? $basename : basename($source);
  $dest = $directory .'/'. $basename;

  // Make sure source and destination filenames are not the same, makes no sense
  // to copy it if they are. In fact copying the file will most likely result in
  // a 0 byte file. Which is bad. Real bad.
  if ($source != realpath($dest)) {
    if (!$dest = file_destination($dest, $replace)) {
      drupal_set_message(t('The selected file %file could not be copied, because a file by that name already exists in the destination.', array('%file' => $source)), 'error');
      return FALSE;
    }

    if (!@copy($source, $dest)) {
      drupal_set_message(t('The selected file %file could not be copied.', array('%file' => $source)), 'error');
      return 0;
    }

    // Give everyone read access so that FTP'd users or
    // non-webserver users can see/read these files,
    // and give group write permissions so group members
    // can alter files uploaded by the webserver.
    @chmod($dest, 0664);
  }

  if (isset($file) && is_object($file)) {
    $file->filename = $basename;
    $file->filepath = $dest;
    $source = $file;
  }
  else {
    $source = $dest;
  }

  return 1; // Everything went ok.
}
?>
Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Вход в систему