Reputation: 558
I am trying to download a large file using the script below. The file downloads, but its named 'download' and the file extension is missing. How can I modify the code below so that the original file name and extension is preserved ? Also is there anyway to automatically detect the mime type and include that as well ?
Thanks a lot in advance.
$path = 'public/Uploads/Films/files/Crank2006.avi';
$size=filesize($path);
$fm=@fopen($path,'rb');
if(!$fm) {
// You can also redirect here
header ("HTTP/1.0 404 Not Found");
die();
}
$begin=0;
$end=$size;
if(isset($_SERVER['HTTP_RANGE'])) {
if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
$begin=intval($matches[0]);
if(!empty($matches[1])) {
$end=intval($matches[1]);
}
}
}
if($begin>0||$end<$size)
header('HTTP/1.0 206 Partial Content');
else
header('HTTP/1.0 200 OK');
header("Content-Type: video/avi");
header('Accept-Ranges: bytes');
header('Content-Length:'.($end-$begin));
header("Content-Disposition: inline;");
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
$cur=$begin;
fseek($fm,$begin,0);
while(!feof($fm)&&$cur<$end&&(connection_status()==0))
{ print fread($fm,min(1024*16,$end-$cur));
$cur+=1024*16;
usleep(1000);
}
die();
Upvotes: 1
Views: 336
Reputation: 2358
Try Something Like Below
$file='test.pdf' //File to download with Large Size
if (file_exists($file)) {
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('backup/'.$file);
return 1;
} else {
return 0;
}
Upvotes: 0
Reputation: 3647
In Content Disposition header you need to specify file name
$file_url = 'what you want to set'
header("Content-disposition: attachment; filename=\"" . $file_url. "\"");
A good tutorial on forced download php here.
For mime type see the following SO post
Upvotes: 1
Reputation: 68476
Just do this below the $path
$path = 'public/Uploads/Films/files/Crank2006.avi';
$filename = array_pop(explode('/',$path)); // Grabbing the filename ... it will be Crank2006.avi
and add the header
with filename to your existing headers.
header("Content-disposition: filename=$filename");
EDIT:
Detecting MIME type...
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);
Upvotes: 0