Php 如何维护响应头

Php 如何维护响应头,php,curl,Php,Curl,我很难理解CURL如何处理标题 我有一个site.com/page1,我想用CURL访问它,它执行308重定向到site.com/page2/file.zip 我需要的是使用CURL浏览site.com/page1,但直接从site.com下载site.com/page2/file.zip 我正在使用这段代码,但它没有按预期工作。它访问site.com/page1重定向到site.com/page2/file.zip,但在浏览器中打开该文件 $ch = curl_init(); curl_se

我很难理解CURL如何处理标题

我有一个
site.com/page1
,我想用CURL访问它,它执行308重定向到
site.com/page2/file.zip

我需要的是使用CURL浏览
site.com/page1
,但直接从site.com下载
site.com/page2/file.zip

我正在使用这段代码,但它没有按预期工作。它访问site.com/page1重定向到site.com/page2/file.zip,但在浏览器中打开该文件

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $_cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $_cookie_file);
curl_setopt($ch, CURLOPT_REFERER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);

curl_exec($ch);
$error = curl_getinfo($ch);
curl_close($ch);

我想如果我能保留响应标题,我就能解决这个问题。但是我该怎么做呢??如何为我访问的站点发送给我的CURL访问者使用相同的标题。

您希望CURL选项
RETURNTRANSFER
设置为
true
,以便返回的内容返回给您。由于您正在尝试保存ZIP文件,您还需要打开一个文件,并使用
CURLOPT_file
选项告诉cURL将ZIP文件保存在何处

curl_setopt ($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_TIMEOUT,'180');  # 3 minute timeout
$FileOut = fopen('MyZIP_File.zip','w') or die('Could not open the output data file');
curl_setopt ($ch, CURLOPT_FILE,$FileOut);
curl_exec   ($ch);
fclose($FileOut) or die('We ran into a problem saving data file');

这就解决了问题

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $_cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $_cookie_file);
curl_setopt($ch, CURLOPT_REFERER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);

$result = curl_exec($ch);
if (preg_match('~Location: (.*)~i', $result, $match)) {
   $location = trim($match[1]);
   header('Location:' . $location);
}

我不想在我的服务器上保存Zip文件,我想让它打开URL,直接从URL保存到计算机上。@BrunoAndrade请解释一下“计算机”是什么意思。只是运行此PHP/cURL代码的机器?然后你仍然需要将接收到的数据保存到一个文件中,这并不是自动发生的…cURL得到了数据,你仍然需要正确地指示它下一步要做什么。我运行cURL的机器是服务器。计算机是使用CURL的访客机器。为了简单起见,我只想知道如何保存我的标题。如果我得到一个308代码,我想把这个308代码传递给访问者。这一点意义不大。为什么访问者不能直接进入第一页并被重定向?为什么卷曲甚至出现在图片中?