Force download a file
Tagged:

The function below forces the download of a file inside a directory 'Log' ( may be any directory Log in my case).All we do here is get the file name inside the directory through GET method and call the custom function force_download.

This function checks if the given file exists in the directory and if it does, it forces the download of the file by printing the required headers to the page. Finally the readfile function outputs the file.


function force_download($file)
{
$dir = "Log/";
if ((isset($file))&&(file_exists($dir.$file))) {
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="' . $dir.$file . '"');
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($dir.$file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile("$dir$file");
} else {
echo "No file selected";
}

}

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