I have a very weird problem with my download script
it basically
1.gets a file id with "GET" method
2.gets the name and location
Your script may contain NOTICE or WARNING, try disabling error reporting on top of your script:
error_reporting(0);
Make sure you do not have any code executed after the last line readfile(FILE_NAME)
I had to add die();
or exit();
as the last line, because MVC framework continues to render the view after readfile
That seems allot of code just to force-download, here is a nice function I use all the time. It will handle files over 2GB too.
<?php
$file_id = (isset($_GET['id']) && (int)$_GET['id'] != 0) ? (int)$_GET['id'] : exit;
/*finding file info*/
$file = comon::get_all_by_condition('files', 'id', $file_id);
$path = $file['location'] . '/' . $file['file_name'];
if (!is_file($path)) {
echo 'File not found.('.$path.')';
} elseif (is_dir($path)) {
echo 'Cannot download folder.';
} else {
send_download($path);
}
return;
//The function with example headers
function send_download($file) {
$basename = basename($file);
$length = sprintf("%u", filesize($file));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $basename . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
readfile($file);
}
?>
Very nice, helpful also...
but there is a problem in your code -
header('Content-Disposition: attachment;
filename="'.basename($file).'"';
please change it with this following -
header('Content-Disposition: attachment;
filename="'.basename($file).'"');
you are forgot to close it.
if (file_exists($file)) {
set_time_limit(0);
header('Connection: Keep-Alive');
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();
flush();
readfile($file);
}