Created
September 19, 2013 07:24
-
-
Save aslamdoctor/6620076 to your computer and use it in GitHub Desktop.
Force file download using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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