1. <?php
  2. /**
  3. * Enforces limits on HTTP response size and attempts fallback.
  4. *
  5. * @param string $data The data to be sent in the response.
  6. * @param int $maxSize The maximum size of the response in bytes.
  7. * @return string The HTTP response.
  8. */
  9. function enforceResponseLimits(string $data, int $maxSize): string
  10. {
  11. // Check if the data exceeds the maximum size.
  12. if (strlen($data) > $maxSize) {
  13. // Fallback: Return a partial response with a helpful message.
  14. $truncatedData = substr($data, 0, $maxSize);
  15. $response = json_encode(['error' => 'Response too large', 'message' => 'Data exceeds maximum allowed size.']); //Use JSON for clarity
  16. $response .= "\n"; // Add a newline for readability
  17. $response .= "truncatedData: " . $truncatedData;
  18. return $response;
  19. } else {
  20. // No truncation needed.
  21. return $data;
  22. }
  23. }
  24. // Example Usage (for testing):
  25. // Simulate a large dataset
  26. $largeData = str_repeat("A", 10000);
  27. // Set the maximum response size (e.g., 10000 characters)
  28. $maxResponseSize = 10000;
  29. // Enforce the limits
  30. $response = enforceResponseLimits($largeData, $maxResponseSize);
  31. // Output the response (for testing)
  32. header('Content-Type: application/json'); //Set content type. Important for API responses
  33. echo $response;
  34. ?>

Add your comment