1 system.module system_retrieve_file($url, $destination = NULL, $managed = FALSE, $replace = FILE_EXISTS_RENAME)

Attempts to get a file using backdrop_http_request and to store it locally.

Parameters

string $url: The URL of the file to grab.

string $destination: Stream wrapper URI specifying where the file should be placed. If a directory path is provided, the file is saved into that directory under its original name. If the path contains a filename as well, that one will be used instead. If this value is omitted, the site's default files scheme will be used, usually "public://".

bool $managed: If this is set to TRUE, the file API hooks will be invoked and the file is registered in the database.

int $replace: Replace behavior when the destination file already exists:

Return value

mixed: One of these possibilities:

  • If it succeeds and $managed is FALSE, the location where the file was saved.
  • If it succeeds and $managed is TRUE, a FileInterface object which describes the file.
  • If it fails, FALSE.

File

core/modules/system/system.module, line 3928
Configuration system that lets administrators modify the workings of the site.

Code

function system_retrieve_file($url, $destination = NULL, $managed = FALSE, $replace = FILE_EXISTS_RENAME) {
  $parsed_url = parse_url($url);
  if (!isset($destination)) {
    $path = file_build_uri(backdrop_basename($parsed_url['path']));
  }
  else {
    if (is_dir(backdrop_realpath($destination))) {
      // Prevent URIs with triple slashes when glueing parts together.
      $path = str_replace('///', '//', "$destination/") . backdrop_basename($parsed_url['path']);
    }
    else {
      $path = $destination;
    }
  }
  $result = backdrop_http_request($url);
  if ($result->code != 200) {
    backdrop_set_message(t('HTTP error @errorcode occurred when trying to fetch @remote.', array('@errorcode' => $result->code, '@remote' => $url)), 'error');
    return FALSE;
  }
  $local = $managed ? file_save_data($result->data, $path, $replace) : file_unmanaged_save_data($result->data, $path, $replace);
  if (!$local) {
    backdrop_set_message(t('@remote could not be saved to @path.', array('@remote' => $url, '@path' => $path)), 'error');
  }

  return $local;
}