You are here

function file_force_file_download in File Force Download 6.2

Same name and namespace in other branches
  1. 5 file_force.module \file_force_file_download()
  2. 6 file_force.module \file_force_file_download()
  3. 7 file_force.module \file_force_file_download()

Implementation of hook_file_download().

This is what adds the headers which activates the force downloading.

File

./file_force.module, line 79
file_force.module

Code

function file_force_file_download($filepath) {
  if (!isset($_GET['download'])) {

    // Our menu hook wasn't called, so we should ignore this.
    return NULL;
  }
  if ($_GET['download'] == 1) {
    $disposition = 'attachment';
  }
  else {
    if ($_GET['download'] == 0) {
      $disposition = 'inline';
    }
    else {

      // We only use 1 and 0.
      return NULL;
    }
  }

  // Generate the full file path for the download
  $filepath = file_create_path($filepath);

  // Try to get the mime type information for the file
  $mimeinfo = '';
  if (function_exists('finfo_open')) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeinfo = finfo_file($finfo, $filepath);
    finfo_close($finfo);
  }
  else {
    if (function_exists('mime_content_type')) {
      $mimeinfo = mime_content_type($filepath);
    }
  }

  // Return a list of headers that will force the download
  return array(
    'Content-Type: ' . $mimeinfo,
    'Content-Disposition: ' . $disposition . '; filename="' . basename($filepath) . '";',
    // Content-Length is also a good header to send, as it allows the browser to
    // display a progress bar correctly.
    // There's a trick for determining the file size for files over 2 GB. Nobody
    // should be using this module with files that large, but… the sprintf()
    // trickery makes sure the value is correct for files larger than 2GB. See
    // note at http://php.net/filesize
    'Content-Length: ' . sprintf('%u', filesize($filepath)),
  );
}