1.20.x file.pages.inc file_download_page($file)

Menu callback; download a single file entity.

File

modules/file/file.pages.inc, line 435
Supports file operations including Manage and Delete.

Code

function file_download_page($file) {
  // If the file does not exist it can cause problems with file_transfer().
  if (!is_file($file->uri)) {
    return MENU_NOT_FOUND;
  }
  // @todo Remove this once backdrop_basename is fixed for PHP versions greater
  //  than '5.3.29'.
  $basename_function = version_compare(PHP_VERSION, '5.3.29', '>') ? 'basename' : 'backdrop_basename';
  $headers = array(
    'Content-Type' => mime_header_encode($file->filemime),
    'Content-Disposition' => 'attachment; filename="' . mime_header_encode($basename_function($file->uri)) . '"',
    'Content-Length' => $file->filesize,
    'Content-Transfer-Encoding' => 'binary',
    'Pragma' => 'no-cache',
    'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
    'Expires' => '0',
  );

  // Let other modules alter the download headers.
  backdrop_alter('file_download_headers', $headers, $file);

  // Let other modules know the file is being downloaded.
  module_invoke_all('file_transfer', $file->uri, $headers);

  if (file_is_local($file)) {
    // For local files, transfer the file and do not reveal the actual URL.
    file_transfer($file->uri, $headers);
  }
  else {
    // For remote files, just redirect the user to that file's actual URL.
    $headers['Location'] = file_create_url($file->uri);
    foreach ($headers as $name => $value) {
      backdrop_add_http_header($name, $value);
    }
    backdrop_send_headers();
    backdrop_exit();
  }
}