Returning header as array using Curl

前端 未结 9 1921
再見小時候
再見小時候 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 04:56

    Fixing issues:

    • Error when content of the header contained ': '(split string)
    • Multiline-headers were not supported
    • Duplicate headers (Set-Cookie) were not supported

    This is my take on the topic ;-)

    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/(?[0-9.]+)\s+(?\d+)(?:\s+(?.*))?$@', $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;
    }
    

提交回复
热议问题