Hide options

Download Script

A simple file download script to force the browser to download the file instead of showing instantly in the browser.
<?php

$filename = stripslashes($_GET['file']);

// workaround for clients using IE. If you have zlib comression disabled on your server by default, you can remove these lines
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  print 'Error, no file selected!';
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  print 'File not found';
  exit;
}

switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/force-download";
}

header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename="".basename($filename)."";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

?>


Description

This download script is useful for sites that have large media files and would like force people to download the files instead of having them run remotely off their web server. This is most commonly applied to mp3's, video clips, pdf files and more.
Example:
Copy paste this script and save it as "download.php". You can use it via the GET query:
http://www.yoursite.com/download.php?file=filepath


Top