1. <?php
  2. /**
  3. * Enforces limits on HTTP header metadata based on a configuration file.
  4. *
  5. * @param array $config Configuration array.
  6. */
  7. function enforceHeaderLimits(array $config): void
  8. {
  9. // Default configuration
  10. $defaultConfig = [
  11. 'max_content_length' => 1024 * 1024, // 1MB default
  12. 'max_connection_heads' => 100,
  13. 'max_date_unparsed' => 3600, // 1 hour
  14. 'max_pipelined_requests' => 10,
  15. 'max_transfer_forwards' => 5,
  16. ];
  17. // Merge default config with provided config
  18. $config = array_merge($defaultConfig, $config);
  19. // Check and enforce max-content-length
  20. if (isset($config['max_content_length'])) {
  21. if (headers_ envoyé) {
  22. if (empty($_SERVER['CONTENT_LENGTH'])) {
  23. $_SERVER['CONTENT_LENGTH'] = 0;
  24. }
  25. if ($_SERVER['CONTENT_LENGTH'] > $config['max_content_length']) {
  26. header('HTTP/1.1 413 Payload Too Large');
  27. exit('Payload too large. Maximum allowed size is ' . $config['max_content_length'] . ' bytes.');
  28. }
  29. }
  30. }
  31. // Check and enforce max-connection-heads
  32. if (isset($config['max_connection_heads'])) {
  33. if (count($_SERVER['HTTP_CONNECTION_HEADS']) > $config['max_connection_heads']) {
  34. header('HTTP/1.1 429 Too Many Connections');
  35. exit('Too many connections. Maximum allowed is ' . $config['max_connection_heads']);
  36. }
  37. }
  38. // Check and enforce max-date-unparsed
  39. if (isset($config['max_date_unparsed'])) {
  40. $date = isset($_SERVER['HTTP_DATE']) ? $_SERVER['HTTP_DATE'] : null;
  41. if ($date) {
  42. $date_timestamp = strtotime($date);
  43. if ($date_timestamp === false || $date_timestamp < time() - $config['max_date_unparsed']) {
  44. header('HTTP/1.1 410 Gone');
  45. exit('Date is too far in the past. Maximum allowed age is ' . $config['max_date_unparsed'] . ' seconds.');
  46. }
  47. }
  48. }
  49. // Check and enforce max-pipelined-requests
  50. if (isset($config['max_pipelined_requests'])) {
  51. if (count($_SERVER['HTTP_PIPELINED_REQUESTS']) > $config['max_pipelined_requests']) {
  52. header('HTTP/1.1 429 Too Many Pipelined Requests');
  53. exit('Too many pipelined requests. Maximum allowed is ' . $config['max_pipelined_requests']);
  54. }
  55. }
  56. // Check and enforce max-transfer-forwards
  57. if (isset($config['max_transfer_forwards'])) {
  58. if (count($_SERVER['HTTP_TRANSFER_FORWARDS']) > $config['max_transfer_forwards']) {
  59. header('HTTP/1.1 429 Too Many Forwarded Requests');
  60. exit('Too many forwarded requests. Maximum allowed is ' . $config['max_transfer_forwards']);
  61. }
  62. }
  63. }
  64. // Example usage (assuming config file exists)
  65. // Read configuration from file (example)
  66. $config = require 'config.php'; // Create config.php with your settings
  67. //Enforce limits
  68. enforceHeaderLimits($config);
  69. ?>

Add your comment