Created
September 5, 2025 18:19
-
-
Save gbhorwood/41b7b9ed1036a03bf7b7ce8e197cc01d to your computer and use it in GitHub Desktop.
curl header parsing functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Extract response headers from curl result as array keyed by header name | |
| * | |
| * @param string $result Return from curl_exec() | |
| * @param CurlHandle $ch Return from curl_init() | |
| * @return array<string,string> | |
| */ | |
| function getCurlResponseHeaders(string $result, CurlHandle $ch): array { | |
| $headersString = substr($result, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE)); | |
| $headersLines = array_values(array_filter(explode(PHP_EOL, $headersString), fn($l) => preg_match('/^[A-Za-z0-9\-]+:/', $l))); | |
| return array_combine(array_map(fn($h) => substr($h, 0, strpos($h, ":")), $headersLines), | |
| array_map(fn($h) => trim(substr($h, strpos($h, ":") + 1)), $headersLines)); | |
| } | |
| /** | |
| * Extract response headers from curl as associated array keyed by header name of arrays of header values | |
| * | |
| * @param string $result The return from curl_exec | |
| * @param CurlHandle $ch The return from curl_init | |
| * @return array<string, <array string>> | |
| */ | |
| function getCurlResponseHeadersArrays(string $result, CurlHandle $ch): array { | |
| $headersString = substr($result, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE)); | |
| $headersLines = array_values(array_filter(explode(PHP_EOL, $headersString), fn($l) => preg_match('/^[A-Za-z0-9\-]+:/', $l))); | |
| $headerKeys = array_unique(array_map(fn($h) => substr($h, 0, strpos($h, ":")), $headersLines)); | |
| $headersArray = []; | |
| foreach($headersLines as $h) { | |
| $headersArray[substr($h, 0, strpos($h, ":"))][] = trim(substr($h, strpos($h, ":") + 1)); | |
| } | |
| return $headersArray; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment