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
if(isset($_POST['expression'])) {
$expression = $_POST['expression'];
if(preg_match('/^[0-9\+\-\*\/\(\) ]+$/', $expression)) {
$result = eval('return ' . $expression . ';');
echo "Result: " . $result;
} else {
echo "Invalid expression";
}
}
?>
Related questions
-
Are there any specific PHP functions or techniques recommended for preventing SQL injection attacks?SQL injection PHP functions prepared statements
-
POST GET form data
-
session management $_SESSION superglobal game state