<?php
/**
* Matches HTTP headers against predefined patterns.
*
* This function provides a simple way to test if HTTP headers
* match specific patterns without requiring extensive configuration.
*
* @param array $headers An associative array of HTTP headers.
* @param array $patterns An array of header patterns. Each pattern
* is an associative array with keys:
* - 'header': The header name (string).
* - 'pattern': A regular expression pattern (string).
* - 'match_type': 'contains' or 'exact' (string).
* @return array An array of matching headers. Each element contains the
* matching header and its corresponding pattern. Returns
* an empty array if no matches are found.
*/
function matchHeaders(array $headers, array $patterns): array
{
$matches = [];
foreach ($patterns as $pattern) {
$headerName = $pattern['header'];
$patternRegex = $pattern['pattern'];
$matchType = $pattern['match_type'];
if (isset($headers[$headerName])) {
$headerValue = $headers[$headerName];
if ($matchType === 'contains') {
if (preg_match($patternRegex, $headerValue)) {
$matches[] = ['header' => $headerName, 'pattern' => $patternRegex];
}
} elseif ($matchType === 'exact') {
if ($headerValue === $patternRegex) {
$matches[] = ['header' => $headerName, 'pattern' => $patternRegex];
}
}
}
}
return $matches;
}
//Example usage
/*
$headers = [
'Content-Type' => 'application/json',
'X-Custom-Header' => 'somevalue',
'Server' => 'Apache/2.4.41',
'Date' => 'Wed, 21 May 2023 12:00:00 GMT'
];
$patterns = [
['header' => 'Content-Type', 'pattern' => '/application\/json/', 'match_type' => 'contains'],
['header' => 'Server', 'pattern' => '/Apache/', 'match_type' => 'contains'],
['header' => 'Date', 'pattern' => '/Wed/', 'match_type' => 'contains'],
['header' => 'X-Custom-Header', 'pattern' => 'somevalue', 'match_type' => 'exact']
];
$matches = matchHeaders($headers, $patterns);
print_r($matches);
*/
?>
Add your comment