【问题标题】:PHP - Download a file from a URLPHP - 从 URL 下载文件
【发布时间】: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,但结果是一样的。

标签: php file audio download


【解决方案1】:

感谢 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;
}

【讨论】:

  • 如果您的函数中有特定的字符串,请始终使用函数参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 2023-01-04
  • 2011-02-14
相关资源
最近更新 更多