我试图卷曲(在PHP中)一个URL并在请求中发送自定义标头。但是我还需要能够查看返回的响应头。我查询了一个我无法控制的外部API。
我尝试过同时使用CURLOPT_HTTPHEADER和CURLOPT_HEADER选项,但它们似乎并不能很好地协同工作。 CURLOPT_HEADER似乎覆盖了请求标头,因此我无法对我的请求进行身份验证,但我可以在响应中查看标头。如果我将CURLOPT_HEADER取出,我可以成功进行身份验证,但无法查看标题。
PHP代码:
$url = "http://url-goes-here";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$headers = array("X-Auth-Token: $token");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 1);
$out = curl_exec($ch);
curl_close($ch);
答案 0 :(得分:0)
根据documentation,它必须是
curl_setopt($ch, CURLOPT_HEADER, 1); // or TRUE
而不是
curl_setopt($ch, CURLOPT_HEADER, $headers);
编辑:我必须说我无法复制这个问题。我创建了两个脚本:a.php(使用你的内容,$ url更改为'http://localhost/b.php')和b.php(由a.php查询)包含:
<?php
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
因此,当我运行php a.php
时,我得到了这个:
HTTP/1.1 200 OK
Date: Tue, 16 Feb 2016 02:42:45 GMT
Server: Apache/2.4.10 (Fedora) PHP/5.6.15
X-Powered-By: PHP/5.6.15
Content-Length: 50
Content-Type: text/html; charset=UTF-8
Host: localhost
Accept: */*
X-Auth-Token: xxx
这意味着我1)成功获得响应标头,2)从a.php
成功接收响应标头。我建议你尝试类似的东西,看看你的网络服务器(或你的应用程序)是否在玩弄你。