What are best practices for validating user input in PHP scripts, especially for temperature values?
When validating user input for temperature values in PHP scripts, it is important to ensure that the input is a valid numeric value within a specific range (e.g., -100 to 100 for temperatures). One approach is to use PHP's filter_var function with the FILTER_VALIDATE_FLOAT filter and then check if the value falls within the desired range.
// Validate user input for temperature value
$input_temperature = $_POST['temperature'];
if (filter_var($input_temperature, FILTER_VALIDATE_FLOAT) !== false) {
$temperature = (float)$input_temperature;
if ($temperature >= -100 && $temperature <= 100) {
// Valid temperature value within range
// Proceed with further processing
} else {
echo "Temperature value must be between -100 and 100 degrees.";
}
} else {
echo "Invalid temperature value. Please enter a valid numeric value.";
}
Keywords
Related Questions
- What are the potential pitfalls of using quantifiers in assertions in PHP regex?
- What impact does the PHP version have on the handling of HTML-Entities in XSLT transformations?
- What are the potential pitfalls of using $_POST['$variable'] instead of assigning it to a variable like $variable = $_POST['variable']?