在我的项目中,我需要下载一个文件,并且需要使用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 文件所在的路径 - 这不是我想要的 - 我需要将文件下载到“下载”文件夹。
所以现在我基本上迷路了。
下载文件的正确方法是什么?
谢谢!
最佳答案
感谢 Google 和大量实验,我成功做到了。
最终代码:
function downloadFile($url, $filename) {
$cURL = curl_init($url);
curl_setopt_array($cURL, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FILE => fopen("Downloads/$filename", "w+"),
CURLOPT_USERAGENT => $_SERVER["HTTP_USER_AGENT"]
]);
$data = curl_exec($cURL);
curl_close($cURL);
header("Content-Disposition: attachment; filename=\"$filename\"");
echo $data;
}
关于PHP - 从 URL 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529049/