Skip to content

Instantly share code, notes, and snippets.

@gbhorwood
Created September 5, 2025 18:19
Show Gist options
  • Select an option

  • Save gbhorwood/41b7b9ed1036a03bf7b7ce8e197cc01d to your computer and use it in GitHub Desktop.

Select an option

Save gbhorwood/41b7b9ed1036a03bf7b7ce8e197cc01d to your computer and use it in GitHub Desktop.
curl header parsing functions
<?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