1. <?php
  2. /**
  3. * Matches HTTP headers against predefined patterns.
  4. *
  5. * This function provides a simple way to test if HTTP headers
  6. * match specific patterns without requiring extensive configuration.
  7. *
  8. * @param array $headers An associative array of HTTP headers.
  9. * @param array $patterns An array of header patterns. Each pattern
  10. * is an associative array with keys:
  11. * - 'header': The header name (string).
  12. * - 'pattern': A regular expression pattern (string).
  13. * - 'match_type': 'contains' or 'exact' (string).
  14. * @return array An array of matching headers. Each element contains the
  15. * matching header and its corresponding pattern. Returns
  16. * an empty array if no matches are found.
  17. */
  18. function matchHeaders(array $headers, array $patterns): array
  19. {
  20. $matches = [];
  21. foreach ($patterns as $pattern) {
  22. $headerName = $pattern['header'];
  23. $patternRegex = $pattern['pattern'];
  24. $matchType = $pattern['match_type'];
  25. if (isset($headers[$headerName])) {
  26. $headerValue = $headers[$headerName];
  27. if ($matchType === 'contains') {
  28. if (preg_match($patternRegex, $headerValue)) {
  29. $matches[] = ['header' => $headerName, 'pattern' => $patternRegex];
  30. }
  31. } elseif ($matchType === 'exact') {
  32. if ($headerValue === $patternRegex) {
  33. $matches[] = ['header' => $headerName, 'pattern' => $patternRegex];
  34. }
  35. }
  36. }
  37. }
  38. return $matches;
  39. }
  40. //Example usage
  41. /*
  42. $headers = [
  43. 'Content-Type' => 'application/json',
  44. 'X-Custom-Header' => 'somevalue',
  45. 'Server' => 'Apache/2.4.41',
  46. 'Date' => 'Wed, 21 May 2023 12:00:00 GMT'
  47. ];
  48. $patterns = [
  49. ['header' => 'Content-Type', 'pattern' => '/application\/json/', 'match_type' => 'contains'],
  50. ['header' => 'Server', 'pattern' => '/Apache/', 'match_type' => 'contains'],
  51. ['header' => 'Date', 'pattern' => '/Wed/', 'match_type' => 'contains'],
  52. ['header' => 'X-Custom-Header', 'pattern' => 'somevalue', 'match_type' => 'exact']
  53. ];
  54. $matches = matchHeaders($headers, $patterns);
  55. print_r($matches);
  56. */
  57. ?>

Add your comment