<?php
/**
* Enforces limits on HTTP header metadata based on a configuration file.
*
* @param array $config Configuration array.
*/
function enforceHeaderLimits(array $config): void
{
// Default configuration
$defaultConfig = [
'max_content_length' => 1024 * 1024, // 1MB default
'max_connection_heads' => 100,
'max_date_unparsed' => 3600, // 1 hour
'max_pipelined_requests' => 10,
'max_transfer_forwards' => 5,
];
// Merge default config with provided config
$config = array_merge($defaultConfig, $config);
// Check and enforce max-content-length
if (isset($config['max_content_length'])) {
if (headers_ envoyé) {
if (empty($_SERVER['CONTENT_LENGTH'])) {
$_SERVER['CONTENT_LENGTH'] = 0;
}
if ($_SERVER['CONTENT_LENGTH'] > $config['max_content_length']) {
header('HTTP/1.1 413 Payload Too Large');
exit('Payload too large. Maximum allowed size is ' . $config['max_content_length'] . ' bytes.');
}
}
}
// Check and enforce max-connection-heads
if (isset($config['max_connection_heads'])) {
if (count($_SERVER['HTTP_CONNECTION_HEADS']) > $config['max_connection_heads']) {
header('HTTP/1.1 429 Too Many Connections');
exit('Too many connections. Maximum allowed is ' . $config['max_connection_heads']);
}
}
// Check and enforce max-date-unparsed
if (isset($config['max_date_unparsed'])) {
$date = isset($_SERVER['HTTP_DATE']) ? $_SERVER['HTTP_DATE'] : null;
if ($date) {
$date_timestamp = strtotime($date);
if ($date_timestamp === false || $date_timestamp < time() - $config['max_date_unparsed']) {
header('HTTP/1.1 410 Gone');
exit('Date is too far in the past. Maximum allowed age is ' . $config['max_date_unparsed'] . ' seconds.');
}
}
}
// Check and enforce max-pipelined-requests
if (isset($config['max_pipelined_requests'])) {
if (count($_SERVER['HTTP_PIPELINED_REQUESTS']) > $config['max_pipelined_requests']) {
header('HTTP/1.1 429 Too Many Pipelined Requests');
exit('Too many pipelined requests. Maximum allowed is ' . $config['max_pipelined_requests']);
}
}
// Check and enforce max-transfer-forwards
if (isset($config['max_transfer_forwards'])) {
if (count($_SERVER['HTTP_TRANSFER_FORWARDS']) > $config['max_transfer_forwards']) {
header('HTTP/1.1 429 Too Many Forwarded Requests');
exit('Too many forwarded requests. Maximum allowed is ' . $config['max_transfer_forwards']);
}
}
}
// Example usage (assuming config file exists)
// Read configuration from file (example)
$config = require 'config.php'; // Create config.php with your settings
//Enforce limits
enforceHeaderLimits($config);
?>
Add your comment