【发布时间】:2018-01-30 19:23:50
【问题描述】:
在我的项目中,我需要下载一个文件,我需要使用PHP。
来自 Google 的所有结果最终都不是很有帮助。
结合 2 个结果的代码后,我最终尝试:
function downloadFile($url, $filename) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
header('Content-Description: File Transfer');
header('Content-Type: audio/*');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($data));
readfile($data);
}
结果是一个音频文件,大小为 10KB(应为 3.58MB)。
此代码与建议重复的问题中的代码不同 - 这里有一部分 curl 函数和标题,而问题的答案只有一堆标题。
使用 VLC 打开文件时 - 出现以下错误:
另外,我尝试使用:
file_put_contents($filename, file_get_contents($url));
这导致将文件下载到 PHP 文件所在的路径 - 这不是我想要的 - 我需要将文件下载到下载文件夹。
所以现在我基本上迷路了。
下载文件的适当方式是什么?
谢谢!
【问题讨论】:
-
php, file download的可能重复
-
尝试将
Content-Transfer-Encoding的值改为chunked,但结果是一样的。