<?php
/**
* Sanitizes configuration values provided via CLI.
*
* @param array $argv Array of command-line arguments.
* @return array Sanitized configuration values.
*/
function sanitizeConfig(array $argv): array
{
$config = [];
// Example configuration values with sanitization
$config['log_level'] = sanitizeString($argv[1] ?? 'debug'); // Default to 'debug'
$config['api_key'] = sanitizeString($argv[2] ?? ''); // Allow empty string
$config['port'] = sanitizeInteger($argv[3] ?? 8080); // Default to 8080
$config['timeout'] = sanitizeInteger($argv[4] ?? 30); // Default to 30
$config['debug_mode'] = sanitizeBoolean($argv[5] ?? false); // Default to false
return $config;
}
/**
* Sanitizes a string, removing potentially harmful characters.
* @param string $string The string to sanitize.
* @return string The sanitized string.
*/
function sanitizeString(string $string): string
{
$string = trim($string); // Remove leading/trailing whitespace
$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); // Escape HTML entities
return $string;
}
/**
* Sanitizes an integer, ensuring it's a valid positive integer.
* @param string $string The string to sanitize.
* @return int The sanitized integer, or a default value if invalid.
*/
function sanitizeInteger(string $string): int
{
$value = filter_var($string, FILTER_VALIDATE_INT); // Validate as integer
return $value === false ? 0 : $value; // Default to 0 if not valid
}
/**
* Sanitizes a boolean value.
* @param string $string The string to sanitize.
* @return bool The sanitized boolean value.
*/
function sanitizeBoolean(string $string): bool
{
$string = strtolower($string); // Convert to lowercase for case-insensitive comparison
return in_array($string, ['true', '1', 'yes'], true); // Check for 'true', '1', or 'yes'
}
// Example usage (uncomment to test from CLI)
/*
$argv = $argv; //This line is needed for the code to work when executed in a CLI
$config = sanitizeConfig($argv);
print_r($config);
*/
?>
Add your comment