【问题标题】:file download with curl and php使用 curl 和 php 下载文件
【发布时间】:2015-06-10 21:14:50
【问题描述】:

我编写了一个使用 curl 扩展名下载一些 (.exe) 文件的 php 函数。该文件已成功下载,但是当我尝试打开它时出现不兼容错误。我使用记事本++打开它,我看到文件开头添加了一个“200”。我真的不明白这个“200”是从哪里来的? 这是我的功能:

$source = isset($_GET['link']) ? $_GET['link'] : ''; #get the download link
$filename = isset($_GET['name']) ? $_GET['name'] : 'download.exe'; # define name
if($source != '')
{
            $handle = curl_init($source);
            curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

            /* Get the HTML or whatever is linked in $url. */
            $response = curl_exec($handle);

            /* Check for 403 (forbidden). */
            $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
            if($httpCode == 403) {
                echo "<h2> <font color='red'> Sorry you are not allowed to download that file.</font><h2>";
            } else {
                header("Content-Disposition: attachment; filename=\"{$filename}\"");
                #header("Content-Disposition: attachment; filename=\"uploaded.pdf\"");
                // Get a FILE url to my test document

                $url= str_replace(" ","%20", $source);
                $ch= curl_init($url);
                #curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
                curl_exec($ch);
                curl_close ($ch); 
             }
            curl_close($handle);
}
else {
echo "error";
}

【问题讨论】:

  • 200 是http响应码表示OK。
  • 是的,我知道,但为什么它写在文件里面?

标签: php curl download


【解决方案1】:

将 CURLOPT_HEADER 设置为 false,例如:

curl_setopt($ch, CURLOPT_HEADER, false);

它将禁用 HTTP 响应,因此您不会在文件中收到“200”。

Similar question here in SO

【讨论】:

  • 您是否知道为什么只有在 Firefox 中才能下载文件末尾带有 .htm 的文件?
  • 不幸的是,我不知道。但是您可以尝试在curl_exec 之后执行echo curl_getinfo($ch, CURLINFO_CONTENT_TYPE); 以查看文件的类型。也许它可以帮助您理解 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
相关资源
最近更新 更多