Skip to content

Instantly share code, notes, and snippets.

@aslamdoctor
Created September 19, 2013 07:24
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 aslamdoctor/6620076 to your computer and use it in GitHub Desktop.
Save aslamdoctor/6620076 to your computer and use it in GitHub Desktop.
Force file download using PHP
<?php
function download_file($file){
$file = $file; //Set File Location
if (file_exists($file)) { // Check if file exists
if(!is_dir($file)){ // Check if it is a directory or a file
// The following files will set the headers to the file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean(); // Clear any set cookies/headers.
flush(); // Flush
readfile($file); // Actually Start The Download
return "Downloading $file"; // Return Downloading FILE_NAME
exit; // Stop Processing
}else{ // If file is a directory
return "You have selected to download a directory. Download Cancelled"; // Show error
}
}else{ // If file doesnt exist
return "File doesnt exist";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment