1. <?php
  2. /**
  3. * Enforces limits on command-line options with manual overrides.
  4. *
  5. * This script provides a temporary solution for limiting command-line option values.
  6. * It allows for manual overrides using environment variables.
  7. */
  8. /**
  9. * Function to validate and limit a command-line option.
  10. *
  11. * @param string $option_name The name of the option.
  12. * @param string $option_value The value of the option from the command line.
  13. * @param int|null $max_value The maximum allowed value. Null if no limit.
  14. * @param string|null $override_env The environment variable to override the limit.
  15. * @return string|false The validated option value, or false if validation fails.
  16. */
  17. function validateOption(string $option_name, string $option_value, ?int $max_value, ?string $override_env): string|false
  18. {
  19. // Check if the override environment variable is set.
  20. if ($override_env && getenv($override_env) !== null) {
  21. $override_value = (int)getenv($override_env);
  22. if ($override_value === false) {
  23. error_log("Invalid value for override environment variable: " . $override_env);
  24. return false;
  25. }
  26. $option_value = $override_value;
  27. }
  28. // Validate the option value based on the maximum value.
  29. if ($max_value !== null && (int)$option_value > $max_value) {
  30. error_log("Option '$option_name' value exceeds maximum allowed value: $max_value.");
  31. return false;
  32. }
  33. return $option_value;
  34. }
  35. // Example usage:
  36. $max_value = 100; // Maximum allowed value for the 'amount' option.
  37. $override_env = 'AMOUNT_OVERRIDE'; // Environment variable to override the limit.
  38. // Simulate command-line option parsing (replace with your actual parsing logic).
  39. $amount = $_GET['amount'] ?? 50; // Default value if not provided.
  40. // Validate the 'amount' option.
  41. $validated_amount = validateOption('amount', $amount, $max_value, $override_env);
  42. if ($validated_amount !== false) {
  43. echo "Validated amount: " . $validated_amount . "\n";
  44. // Use the validated amount.
  45. } else {
  46. echo "Invalid amount provided.\n";
  47. }
  48. //Another example
  49. $filename = $_GET['filename'] ?? 'default.txt';
  50. //Validate filename
  51. $validated_filename = validateOption('filename', $filename, null, $override_env);
  52. if ($validated_filename !== false) {
  53. echo "Validated filename: " . $validated_filename . "\n";
  54. } else {
  55. echo "Invalid filename provided.\n";
  56. }
  57. ?>

Add your comment