Skip to content

Instantly share code, notes, and snippets.

@solepixel
Created August 29, 2015 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solepixel/ff2194493f74cb999306 to your computer and use it in GitHub Desktop.
Save solepixel/ff2194493f74cb999306 to your computer and use it in GitHub Desktop.
Force Download Snippet
<?php
$filename = $my_file_name;
if(substr($filename,0,1) != "/"){
$filename = "/". $filename;
}
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" ) {
header("Location: /error.php?nofile");
} elseif ( !file_exists( $filename ) ){
header("Location: /error.php?file404");
};
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 "js" : $ctype="application/x-javascript"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment