1. <?php
  2. /**
  3. * Sanitizes configuration values provided via CLI.
  4. *
  5. * @param array $argv Array of command-line arguments.
  6. * @return array Sanitized configuration values.
  7. */
  8. function sanitizeConfig(array $argv): array
  9. {
  10. $config = [];
  11. // Example configuration values with sanitization
  12. $config['log_level'] = sanitizeString($argv[1] ?? 'debug'); // Default to 'debug'
  13. $config['api_key'] = sanitizeString($argv[2] ?? ''); // Allow empty string
  14. $config['port'] = sanitizeInteger($argv[3] ?? 8080); // Default to 8080
  15. $config['timeout'] = sanitizeInteger($argv[4] ?? 30); // Default to 30
  16. $config['debug_mode'] = sanitizeBoolean($argv[5] ?? false); // Default to false
  17. return $config;
  18. }
  19. /**
  20. * Sanitizes a string, removing potentially harmful characters.
  21. * @param string $string The string to sanitize.
  22. * @return string The sanitized string.
  23. */
  24. function sanitizeString(string $string): string
  25. {
  26. $string = trim($string); // Remove leading/trailing whitespace
  27. $string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); // Escape HTML entities
  28. return $string;
  29. }
  30. /**
  31. * Sanitizes an integer, ensuring it's a valid positive integer.
  32. * @param string $string The string to sanitize.
  33. * @return int The sanitized integer, or a default value if invalid.
  34. */
  35. function sanitizeInteger(string $string): int
  36. {
  37. $value = filter_var($string, FILTER_VALIDATE_INT); // Validate as integer
  38. return $value === false ? 0 : $value; // Default to 0 if not valid
  39. }
  40. /**
  41. * Sanitizes a boolean value.
  42. * @param string $string The string to sanitize.
  43. * @return bool The sanitized boolean value.
  44. */
  45. function sanitizeBoolean(string $string): bool
  46. {
  47. $string = strtolower($string); // Convert to lowercase for case-insensitive comparison
  48. return in_array($string, ['true', '1', 'yes'], true); // Check for 'true', '1', or 'yes'
  49. }
  50. // Example usage (uncomment to test from CLI)
  51. /*
  52. $argv = $argv; //This line is needed for the code to work when executed in a CLI
  53. $config = sanitizeConfig($argv);
  54. print_r($config);
  55. */
  56. ?>

Add your comment