PHP Curl从https URL下载空文件(.gz)


PHP Curl downloads empty file(.gz) from a https URL

我正试图通过身份验证从https URL下载.xml.gz文件。

这是我当前的代码。

    $remote_file = 'https://path/filename.xml.gz';
    $local_file = "test.xml.gz";
    $username ="21";
    $password ="qwerty";
    $ch = curl_init($remote_file);
    $headers = array('Content-type: application/x-gzip','Connection: Close');
    $fp = fopen ($local_file, 'wb');
    curl_setopt($ch, CURLOPT_URL,$remote_file);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_SSLVERSION,3);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 50);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
    $data = curl_exec($ch);
    if(fwrite($fp,$data))
    {
     echo "success";
    }
    else
    {
     echo "fail";
    }
    curl_close($ch);
    fclose($fp);

执行后,将创建test.xml.gz文件,但该文件为空。

我认为问题在于连接到https页面中的文件。当我尝试从非https url下载文件时,代码似乎运行良好。

奇怪的是,curl没有显示任何错误

使用curl verbose输出跟踪后,我发现问题出在$headers上。显然,删除$headers并替换为curl_setopt($curl,CURLOPT_HEADER,true)正如预期的那样。

这是最后的代码。

$fp = fopen($local_file, 'wb');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $remote_file);
$result = curl_exec($ch);
$write = fwrite($fp,$result);

您需要将curl_exec的结果存储到一个变量中:

$fileContents = curl_exec($ch);

然后将文件的内容写入本地文件:

fwrite($fp, $fileContents);

然后它应该按要求工作。