PHP - 从URL下载文件

时间:2018-01-30 19:23:50

标签: php file audio download

在我的项目中,我需要下载一个文件,我需要使用PHP 谷歌的所有结果最终都没有帮助。

在合并了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文件所在的路径 - 这不是我想要的 - 我需要将文件下载到Downloads文件夹。

所以现在我基本上迷路了 下载文件的适当方式是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

由于谷歌和大量实验,我成功地做到了 最终代码:

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;
}
相关问题