Я не могу загрузить скрипт загрузки для работы с внешними файлами, файл будет загружен, но поврежден/не работает. Я думаю, это потому, что я не могу получить размер файла внешнего файла с функцией filesize().Загрузить внешний файл с PHP fopen и/или cURL
Это мой сценарий:
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;
}
}
Я считаю, что это можно сделать с помощью Curl - но мои знания не хватает. То, что я хотел бы знать:
Как проверить, если файл существует и как я могу получить размер файла с Curl?
Было бы лучше просто использовать cURL и забыть о fopen?
Правильно ли установлены заголовки?
Любые советы очень ценятся!
Что происходит, когда вы опускаете заголовок Content-Length :. Можете ли вы загрузить весь файл перед его выпуском? – iewebguy
Просьба указать некоторые результаты попытки отладки проблемы. –
ОТВЕТ: ДА, забудьте о 'fopen' и используйте' curl'. – khael