How can PHP be used to handle user input for mathematical formulas in a web application effectively?

When handling user input for mathematical formulas in a web application, it is important to validate and sanitize the input to prevent security risks such as SQL injection or code execution. One way to effectively handle user input is to use PHP's built-in functions like `filter_input()` to validate and sanitize the input data before processing it in mathematical calculations.

// Get user input from a form field named 'formula'
$formula = filter_input(INPUT_POST, 'formula', FILTER_SANITIZE_STRING);

// Validate the input to ensure it is a valid mathematical formula
if (preg_match('/^[0-9\(\)\+\-\*\/\.\s]+$/', $formula)) {
    // Evaluate the mathematical formula using eval() function
    $result = eval("return $formula;");
    echo "Result: $result";
} else {
    echo "Invalid input. Please enter a valid mathematical formula.";
}