29

我正在尝试使用 PHP 从 CURL 获取响应和响应标头,特别是对于 Content-Disposition: attachment; 所以我可以返回在标题中传递的文件名。这似乎没有在 curl_getinfo 中返回。

我尝试使用 HeaderFunction 调用函数来读取附加标题,但是,我无法将内容添加到数组中。

请问有人有什么想法吗?


下面是我的代码的一部分,它是一个 Curl 包装器类:

 ...
 curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
 curl_setopt($this->_ch, CURLOPT_HEADER, false);
 curl_setopt($this->_ch, CURLOPT_POST, 1);
 curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $this->_postData);
 curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_userAgent);
 curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, 'readHeader');

 $this->_response = curl_exec($this->_ch);
 $info = curl_getinfo($this->_ch);
 ...


 function readHeader($ch, $header)
 {
      array_push($this->_headers, $header);
 }
4

9 回答 9

75

在这里,应该这样做:

curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
curl_setopt($this->_ch, CURLOPT_HEADER, 1);
curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($this->_ch);
$info = curl_getinfo($this->_ch);

$headers = get_headers_from_curl_response($response);

function get_headers_from_curl_response($response)
{
    $headers = array();

    $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));

    foreach (explode("\r\n", $header_text) as $i => $line)
        if ($i === 0)
            $headers['http_code'] = $line;
        else
        {
            list ($key, $value) = explode(': ', $line);

            $headers[$key] = $value;
        }

    return $headers;
}
于 2012-05-14T20:03:08.727 回答
33

c.hill 的 anwser 很棒,但如果第一个响应是 301 或 302,代码将无法处理 - 在这种情况下,只有第一个标头将添加到 get_header_from_curl_response() 返回的数组中。

我已经更新了函数以返回一个包含每个标题的数组。

首先,我使用这些行创建一个仅包含标题内容的变量

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($a, 0, $header_size);

比我将 $header 传递给新的 get_headers_from_curl_response() 函数:

static function get_headers_from_curl_response($headerContent)
{

    $headers = array();

    // Split the string on every "double" new line.
    $arrRequests = explode("\r\n\r\n", $headerContent);

    // Loop of response headers. The "count() -1" is to 
    //avoid an empty row for the extra line break before the body of the response.
    for ($index = 0; $index < count($arrRequests) -1; $index++) {

        foreach (explode("\r\n", $arrRequests[$index]) as $i => $line)
        {
            if ($i === 0)
                $headers[$index]['http_code'] = $line;
            else
            {
                list ($key, $value) = explode(': ', $line);
                $headers[$index][$key] = $value;
            }
        }
    }

    return $headers;
}

此函数将采用如下标题:

HTTP/1.1 302 Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Location: http://www.website.com/
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Sun, 08 Sep 2013 10:51:39 GMT
Connection: close
Content-Length: 16313

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Sun, 08 Sep 2013 10:51:39 GMT
Connection: close
Content-Length: 15519

并返回一个这样的数组:

(
    [0] => Array
        (
            [http_code] => HTTP/1.1 302 Found
            [Cache-Control] => no-cache
            [Pragma] => no-cache
            [Content-Type] => text/html; charset=utf-8
            [Expires] => -1
            [Location] => http://www.website.com/
            [Server] => Microsoft-IIS/7.5
            [X-AspNet-Version] => 4.0.30319
            [Date] => Sun, 08 Sep 2013 10:51:39 GMT
            [Connection] => close
            [Content-Length] => 16313
        )

    [1] => Array
        (
            [http_code] => HTTP/1.1 200 OK
            [Cache-Control] => private
            [Content-Type] => text/html; charset=utf-8
            [Server] => Microsoft-IIS/7.5
            [X-AspNet-Version] => 4.0.30319
            [Date] => Sun, 08 Sep 2013 10:51:39 GMT
            [Connection] => close
            [Content-Length] => 15519
        )

)
于 2013-09-08T10:55:28.020 回答
1

使用array()方法回调的形式应该使原始示例工作:

curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, array($this, 'readHeader'));

于 2013-06-12T12:30:39.597 回答
1

修复问题:

  • 标头内容包含“:”(拆分字符串)时出错
  • 不支持多行标题
  • 不支持重复的标头 (Set-Cookie)

这是我对这个话题的看法;-)

list($head, $body)=explode("\r\n\r\n", $content, 2);
$headers=parseHeaders($head); 

function parseHeaders($text) {
    $headers=array();

    foreach (explode("\r\n", $text) as $i => $line) {
        // Special HTTP first line
        if (!$i && preg_match('@^HTTP/(?<protocol>[0-9.]+)\s+(?<code>\d+)(?:\s+(?<message>.*))?$@', $line, $match)) {
            $headers['@status']=$line;
            $headers['@code']=$match['code'];
            $headers['@protocol']=$match['protocol'];
            $headers['@message']=$match['message'];
            continue;
        }

        // Multiline header - join with previous
        if ($key && preg_match('/^\s/', $line)) {
            $headers[$key].=' '.trim($line);
            continue;
        }

        list ($key, $value) = explode(': ', $line, 2);
        $key=strtolower($key);
        // Append duplicate headers - namely Set-Cookie header
        $headers[$key]=isset($headers[$key]) ? $headers[$key].' ' : $value;
    }

    return $headers;
}
于 2019-05-29T11:41:32.373 回答
1

我的另一个实现:

function getHeaders($response){

    if (!preg_match_all('/([A-Za-z\-]{1,})\:(.*)\\r/', $response, $matches) 
            || !isset($matches[1], $matches[2])){
        return false;
    }

    $headers = [];

    foreach ($matches[1] as $index => $key){
        $headers[$key] = $matches[2][$index];
    }

    return $headers;
}

用于case,请求格式为:

主持人:*
接受:*
内容长度:*
等等...

于 2017-06-01T09:19:24.463 回答
1

简单明了

$headers = [];
// Get the response body as string
$response = curl_exec($curl);
// Get the response headers as string
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
// Get the substring of the headers and explode as an array by \r\n
// Each element of the array will be a string `Header-Key: Header-Value`
// Retrieve this two parts with a simple regex `/(.*?): (.*)/`
foreach(explode("\r\n", trim(substr($response, 0, $headerSize))) as $row) {
    if(preg_match('/(.*?): (.*)/', $row, $matches)) {
        $headers[$matches[1]] = $matches[2];
    }
}
于 2017-06-22T11:44:35.747 回答
0

C.hill 的答案很棒,但在检索多个 cookie 时会中断。在这里进行了更改

public function get_headers_from_curl_response($response) { 
    $headers = array(); 
    $header_text = substr($response, 0, strpos($response, "\r\n\r\n")); 
    foreach (explode("\r\n", $header_text) as $i => $line) 
         if ($i === 0) $headers['http_code'] = $line; 
         else { 
              list ($key, $value) = explode(': ', $line); $headers[$key][] = $value; 
         } 
    return $headers; 
}
于 2018-04-10T17:00:15.773 回答
-1

您可以使用http_parse_headers函数。

它来自PECL,但你会在这个 SO 线程中找到后备

于 2015-09-09T10:09:57.927 回答
-3

你可以做两种方式

  1. 通过设置 curl_setopt($this->_ch, CURLOPT_HEADER, true); 标头将带有来自 curl_exec() 的响应消息;您必须从响应消息中搜索关键字“Content-Disposition:”。

  2. 在调用 curl_exec() 后立即使用此函数 get_headers($url)。$url 是 curl 中调用的 url。返回是标题数组。在数组中搜索“Content-Disposition”以获得您想要的。

于 2012-09-16T17:37:11.683 回答