1. <?php
  2. /**
  3. * Sanitizes JSON input to prevent potential vulnerabilities.
  4. *
  5. * This function takes a JSON string as input and sanitizes it to remove
  6. * potentially harmful characters or structures. It's designed for testing
  7. * and should not be considered a comprehensive security solution for production
  8. * environments.
  9. *
  10. * @param string $json_string The JSON string to sanitize.
  11. * @return string|null The sanitized JSON string, or null if sanitization fails.
  12. */
  13. function sanitizeJson(string $json_string): ?string
  14. {
  15. // Remove potentially harmful characters. This is a basic example;
  16. // consider a more comprehensive character filtering approach for production.
  17. $sanitized_string = preg_replace('/[<>&"\'\\]/', '', $json_string);
  18. // Validate the JSON structure. This prevents invalid JSON from being processed.
  19. $decoded = json_decode($sanitized_string);
  20. if (json_last_error() !== JSON_ERROR_NONE) {
  21. // JSON decoding failed. Return null to indicate an error.
  22. error_log("JSON decoding error: " . json_last_error_msg()); // Log the error
  23. return null;
  24. }
  25. // If decoding was successful, return the original JSON string.
  26. return $sanitized_string;
  27. }
  28. // Example usage (for testing)
  29. $test_json = '{ "name": "John Doe", "age": 30, "city": "New York" , "description": "This is a test" }';
  30. $sanitized_json = sanitizeJson($test_json);
  31. if ($sanitized_json !== null) {
  32. echo "Sanitized JSON:\n";
  33. echo $sanitized_json . "\n";
  34. } else {
  35. echo "Sanitization failed.\n";
  36. }
  37. // Example with potentially malicious input
  38. $malicious_json = '{"name": "Test <script>alert(\'XSS\')</script>"}';
  39. $sanitized_malicious_json = sanitizeJson($malicious_json);
  40. if ($sanitized_malicious_json !== null) {
  41. echo "Sanitized Malicious JSON:\n";
  42. echo $sanitized_malicious_json . "\n";
  43. } else {
  44. echo "Sanitization failed.\n";
  45. }
  46. ?>

Add your comment