用curl和php下载文件

时间:2015-06-10 13:10:29

标签: php curl download

我写了一个php函数,它使用curl扩展名下载一些(.exe)文件。该文件已成功下载,但当我尝试打开它时,我得到了不兼容的错误。我用记事本++打开它,在那里我看到了一个' 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";
}

1 个答案:

答案 0 :(得分:0)

将CURLOPT_HEADER设置为false,如:

curl_setopt($ch, CURLOPT_HEADER, false);

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

Similar question here in SO