<?php
/**
* Sanitizes and validates user input for internal use.
*
* @param string $input The user-provided input.
* @param string $type The expected data type ('string', 'int', 'float', 'array').
* @param string $name The name of the input field (for logging/debugging).
* @param string $allowed_values (Optional) An array of allowed values.
* @param string $error_message The message to display on validation failure.
*
* @return mixed The sanitized and validated input, or null on failure.
*/
function sanitizeAndValidateInput(string $input, string $type, string $name, array $allowed_values = [], string $error_message = "Invalid input.") {
// Sanitize input - remove potentially harmful characters.
$sanitized_input = trim(htmlspecialchars($input));
// Type validation.
switch ($type) {
case 'string':
if (!is_string($sanitized_input)) {
error_log("Invalid input type for field: " . $name . ". Expected string.");
return null;
}
break;
case 'int':
if (!is_int($sanitized_input)) {
error_log("Invalid input type for field: " . $name . ". Expected integer.");
return null;
}
break;
case 'float':
if (!is_float($sanitized_input)) {
error_log("Invalid input type for field: " . $name . ". Expected float.");
return null;
}
break;
case 'array':
if (!is_array($sanitized_input)) {
error_log("Invalid input type for field: " . $name . ". Expected array.");
return null;
}
break;
default:
error_log("Invalid input type for field: " . $name . ". Unknown type: " . $type);
return null;
}
// Check for empty input.
if (empty($sanitized_input)) {
error_log("Input for field: " . $name . " is empty.");
return null;
}
// Validate against allowed values.
if (!empty($allowed_values) && !in_array($sanitized_input, $allowed_values)) {
error_log("Input for field: " . $name . " is not in the allowed values: " . json_encode($allowed_values));
return null;
}
// Return the sanitized and validated input.
return $sanitized_input;
}
// Example Usage:
// $user_input = $_POST['username'];
// $username = sanitizeAndValidateInput($user_input, 'string', 'username', [], 'Username is invalid.');
?>
Add your comment