I can't get my download script to work with external files, the file will download but is corrupted/not working. I think it's because I can't get the filesize of the external file with filesize() function.
This is my script:
function getMimeType($filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = strtolower($ext);
$mime_types=array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain",
"csv" => "text/csv",
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
);
if(isset($mime_types[$ext])){
return $mime_types[$ext];
} else {
return 'application/octet-stream';
}
}
$path = "http://www.example.com/file.zip";
/* Does not work on external files
// check file is readable or not exists
if (!is_readable($path))
die('File is not readable or does not exists!');
*/
$file_headers = @get_headers($path);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
echo "Files does not exist.";
} else {
$filename = pathinfo($path, PATHINFO_BASENAME);
// get mime type of file by extension
$mime_type = getMimeType($filename);
// set headers
header('Pragma: public');
header('Expires: -1');
header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Length: " . filesize($path));
header("Content-Type: $mime_type");
header("Content-Description: File Transfer");
// read file as chunk
if ( $fp = fopen($path, 'rb') ) {
ob_end_clean();
while( !feof($fp) and (connection_status()==0) ) {
print(fread($fp, 8192));
flush();
}
@fclose($fp);
exit;
}
}
I believe it can be done with cURL - but my knowledge is lacking. What I would like to know:
How do I check if the file exist and how do I get the filesize with cURL?
Would it be better just to use cURL and forget about fopen?
Is the headers set correctly?
Any advice is much appreciated!