Returning header as array using Curl

前端 未结 9 1903
再見小時候
再見小時候 2020-12-01 04:22

I\'m trying to get the response & the response headers from CURL using PHP, specifically for Content-Disposition: attachment; so I can return the filename passed within

相关标签:
9条回答
  • 2020-12-01 05:17

    Here, this should do it:

    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;
    }
    
    0 讨论(0)
  • 2020-12-01 05:19

    You can use http_parse_headers function.

    It comes from PECL but you will find fallbacks in this SO thread.

    0 讨论(0)
  • 2020-12-01 05:21

    Simple and straightforward

    $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];
        }
    }
    
    0 讨论(0)
提交回复
热议问题