从PHP cURL POST请求中获取头信息

12

我已经搜索了几个小时,但没有找到相关的内容。我正在使用php curl进行post请求到Sugarsync API,并且它会在响应头中返回一个位置信息,我需要这个信息。由于我要向他们的API提交XML文件并且他们只返回头信息,所以必须保持post方式。我不知道如何获取响应头中的位置信息。根据他们的说法,我需要将其放入另一个XML文件中,并再次提交post请求。非常感谢您的帮助。

2个回答

16

如果您设置了curl选项CURLOPT_FOLLOWLOCATION,curl将会自动跟随重定向的位置。

如果您想获取头信息,将选项CURLOPT_HEADER设置为1,从curl_exec()返回的HTTP响应将包含头信息。您可以解析这些响应头来获得位置信息。

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1); // return HTTP headers with response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return the response rather than output it

$resp = curl_exec($ch);

list($headers, $response) = explode("\r\n\r\n", $resp, 2);
// $headers now has a string of the HTTP headers
// $response is the body of the HTTP response

$headers = explode("\n", $headers);
foreach($headers as $header) {
    if (stripos($header, 'Location:') !== false) {
        echo "The location header is: '$header'";
    }
}

请查看curl_setopt()以获取所有选项。


2
获取响应中的头部信息。
curlsetopt($ch,CURLOPT_HEADER,true);

1
这个程序给了我头部信息,但是我该如何解析它以获取特定的位置信息? - selanac82

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接