1. <?php
  2. /**
  3. * Guards execution of HTTP requests for monitoring purposes.
  4. * This code does not use async logic.
  5. *
  6. * @param callable $callback The function to be executed.
  7. * @return void
  8. */
  9. function monitorHttpRequest(callable $callback)
  10. {
  11. // Log the request details.
  12. $startTime = microtime(true);
  13. $requestData = func_get_args(); // Get all arguments passed to the function
  14. $requestMethod = $_SERVER['REQUEST_METHOD'];
  15. $requestUrl = $_SERVER['REQUEST_URI'];
  16. $userAgent = $_SERVER['HTTP_USER_AGENT'];
  17. // Execute the callback.
  18. $result = $callback(...$requestData);
  19. $endTime = microtime(true);
  20. $executionTime = $endTime - $startTime;
  21. // Log the execution time and other details.
  22. error_log("Request: Method={$requestMethod}, URL={$requestUrl}, User Agent={$userAgent}, Execution Time={$executionTime} seconds");
  23. //Return the result from the callback
  24. return $result;
  25. }
  26. // Example Usage (replace with your actual function)
  27. /*
  28. function myEndpoint($param1, $param2) {
  29. // Your endpoint logic here.
  30. return "Endpoint processed with: " . $param1 . " and " . $param2;
  31. }
  32. //Call the monitored function
  33. $result = monitorHttpRequest("myEndpoint", "value1", "value2");
  34. echo $result;
  35. */
  36. ?>

Add your comment