1. <?php
  2. /**
  3. * Sanitizes and validates user input for internal use.
  4. *
  5. * @param string $input The user-provided input.
  6. * @param string $type The expected data type ('string', 'int', 'float', 'array').
  7. * @param string $name The name of the input field (for logging/debugging).
  8. * @param string $allowed_values (Optional) An array of allowed values.
  9. * @param string $error_message The message to display on validation failure.
  10. *
  11. * @return mixed The sanitized and validated input, or null on failure.
  12. */
  13. function sanitizeAndValidateInput(string $input, string $type, string $name, array $allowed_values = [], string $error_message = "Invalid input.") {
  14. // Sanitize input - remove potentially harmful characters.
  15. $sanitized_input = trim(htmlspecialchars($input));
  16. // Type validation.
  17. switch ($type) {
  18. case 'string':
  19. if (!is_string($sanitized_input)) {
  20. error_log("Invalid input type for field: " . $name . ". Expected string.");
  21. return null;
  22. }
  23. break;
  24. case 'int':
  25. if (!is_int($sanitized_input)) {
  26. error_log("Invalid input type for field: " . $name . ". Expected integer.");
  27. return null;
  28. }
  29. break;
  30. case 'float':
  31. if (!is_float($sanitized_input)) {
  32. error_log("Invalid input type for field: " . $name . ". Expected float.");
  33. return null;
  34. }
  35. break;
  36. case 'array':
  37. if (!is_array($sanitized_input)) {
  38. error_log("Invalid input type for field: " . $name . ". Expected array.");
  39. return null;
  40. }
  41. break;
  42. default:
  43. error_log("Invalid input type for field: " . $name . ". Unknown type: " . $type);
  44. return null;
  45. }
  46. // Check for empty input.
  47. if (empty($sanitized_input)) {
  48. error_log("Input for field: " . $name . " is empty.");
  49. return null;
  50. }
  51. // Validate against allowed values.
  52. if (!empty($allowed_values) && !in_array($sanitized_input, $allowed_values)) {
  53. error_log("Input for field: " . $name . " is not in the allowed values: " . json_encode($allowed_values));
  54. return null;
  55. }
  56. // Return the sanitized and validated input.
  57. return $sanitized_input;
  58. }
  59. // Example Usage:
  60. // $user_input = $_POST['username'];
  61. // $username = sanitizeAndValidateInput($user_input, 'string', 'username', [], 'Username is invalid.');
  62. ?>

Add your comment