Skip to content
PHP Logo

How can PHP be used to calculate a variable passed via POST, such as "7+5"?

To calculate a variable passed via POST in PHP, such as "7+5", you can use the eval() function to evaluate the expression. First, retrieve the POST variable using $_POST, then use eval() to calculate the result. It's important to validate the input to ensure it's a valid mathematical expression before using eval() to prevent security risks.

php
<?php
if(isset($_POST['expression'])) {
    $expression = $_POST['expression'];
    if(preg_match('/^[0-9\+\-\*\/\(\) ]+$/', $expression)) {
        $result = eval('return ' . $expression . ';');
        echo "Result: " . $result;
    } else {
        echo "Invalid expression";
    }
}
?>