<?php
/**
* Attaches metadata to HTTP requests for internal tooling.
*
* @param array $options An associative array of options.
* 'request_id' => Unique identifier for the request.
* 'user_id' => User ID making the request.
* 'custom_data' => Associative array of custom data.
* @return array|false Returns an array of headers to add, or false on error.
*/
function attachRequestMetadata(array $options): array|false
{
// Validate options
if (empty($options) || !isset($options['request_id'])) {
error_log("Missing 'request_id' option.");
return false;
}
$request_id = $options['request_id'];
$user_id = isset($options['user_id']) ? $options['user_id'] : 'anonymous'; // Default to anonymous if not provided
$custom_data = isset($options['custom_data']) ? $options['custom_data'] : [];
// Build headers
$headers = [];
// Request ID
$headers[] = 'X-Request-ID: ' . $request_id;
// User ID
$headers[] = 'X-User-ID: ' . $user_id;
// Custom Data
foreach ($custom_data as $key => $value) {
$headers[] = 'X-Custom-' . $key . ': ' . $value;
}
return $headers;
}
/**
* Example usage (replace with your actual framework/application integration)
*/
if (PHP_SAPI === 'cli') {
$options = [
'request_id' => uniqid(),
'user_id' => '123',
'custom_data' => [
'environment' => 'development',
'version' => '1.0',
],
];
$headers = attachRequestMetadata($options);
if ($headers !== false) {
foreach ($headers as $header) {
echo $header . "\n";
}
} else {
echo "Error attaching metadata.\n";
}
}
?>
Add your comment