我正在尝试从带有身份验证的https网址下载.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网址下载文件时,代码似乎工作正常。
奇怪的是,curl没有显示任何错误答案 0 :(得分:1)
您需要将curl_exec的结果存储到变量中:
$fileContents = curl_exec($ch);
然后将文件的内容写入本地文件:
fwrite($fp, $fileContents);
然后它应该按照需要工作。
答案 1 :(得分:1)
使用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);