1. <?php
  2. /**
  3. * Adds metadata to user input for internal tooling.
  4. *
  5. * This function attaches metadata to user input data. It supports
  6. * older PHP versions by using `$_POST` and `$_GET` arrays.
  7. *
  8. * @param array $data The data to add metadata to. Can be $_POST, $_GET, or a custom array.
  9. * @param array $metadata An associative array of metadata key-value pairs.
  10. * @return array The modified data with metadata added. Returns the original data if $data is not an array.
  11. */
  12. function addMetadataToData(array $data, array $metadata): array
  13. {
  14. if (!is_array($data)) {
  15. return $data; // Return original data if not an array
  16. }
  17. // Merge metadata into the data array.
  18. $data = array_merge($data, $metadata);
  19. return $data;
  20. }
  21. /**
  22. * Example usage with $_POST data.
  23. */
  24. if (isset($_POST)) {
  25. $postData = $_POST;
  26. $internalMetadata = [
  27. 'submission_timestamp' => time(),
  28. 'user_agent' => $_SERVER['HTTP_USER_AGENT'],
  29. 'request_ip' => $_SERVER['REMOTE_ADDR'],
  30. 'request_method' => $_SERVER['REQUEST_METHOD']
  31. ];
  32. $metadataWithPost = addMetadataToData($postData, $internalMetadata);
  33. // Now $metadataWithPost contains the original POST data plus the metadata.
  34. // You can then process $metadataWithPost for your internal tooling.
  35. // For example:
  36. // error_log(print_r($metadataWithPost, true)); //Log the data to a file.
  37. //Example of how to access a metadata value
  38. if(isset($metadataWithPost['submission_timestamp'])) {
  39. $timestamp = $metadataWithPost['submission_timestamp'];
  40. error_log("Submission Timestamp: " . $timestamp);
  41. }
  42. } else {
  43. //Example usage with $_GET data
  44. $getData = $_GET;
  45. $internalMetadata = [
  46. 'submission_timestamp' => time(),
  47. 'user_agent' => $_SERVER['HTTP_USER_AGENT'],
  48. 'request_ip' => $_SERVER['REMOTE_ADDR'],
  49. 'request_method' => $_SERVER['REQUEST_METHOD']
  50. ];
  51. $metadataWithGet = addMetadataToData($getData, $internalMetadata);
  52. // Now $metadataWithGet contains the original GET data plus the metadata.
  53. // You can then process $metadataWithGet for your internal tooling.
  54. // For example:
  55. // error_log(print_r($metadataWithGet, true)); //Log the data to a file.
  56. }
  57. ?>

Add your comment