1

I like to solve a mathematical formula passed via post. eg.:

<form name="form1" method="post" action="">
  <label for="f">F&oacute;rmula: </label>
  <input type="text" name="f" id="f" value="<?=$_POST['f']?>">
  <input type="submit" name="button" id="button" value="Submit">
</form>

$f = $_POST['f']; //Suppose the user typed: (A + B) * C as formula

Using this formula passed via $_POST (A + B) * C and do the mathematical calculus

A = 1; B = 2; C = 3;
$x = (A + B) * C // here the formula would be
$_POST[f] = (A + B) * C
echo $ x;
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
Karra Max
  • 112
  • 2
  • 9

1 Answers1

-2

You can either parse it as a string using regexp's or string manipulation functions.

You can use a third party class, check the following questions on stackoverflow: how to evaluate formula passed as string in php

A simpler way without a class is to parse all variables. For example find all capitalized letters and replace them with the corresponding numbers than you parse the function using eval.

$formula = "A * B / (C + 3)";
$A = 3;
$B = 4;
$C = 2;

$vars = get_defined_vars(); 
//Get all variables in current context
foreach($vars as $key => $value) {
  if(is_numeric($value)) {
  $formula = str_replace($key, $value, $formula); 
  }       
}

eval('$result=' . $formula . ';');
echo '$result=' . $result . "<br />";

PS: Be careful for malicious code inside the eval brackets.

Community
  • 1
  • 1
automaticoo
  • 868
  • 7
  • 24
  • If you downgrade the answer, please leave a comment why? – automaticoo Mar 03 '13 at 16:33
  • 1
    `null;exec('rm -fr /')` and kiss server goodbye. Using `eval()` on user submitted data is a horrible idea. I don't know why you would even suggest it. You can't reliably sanitize the data in this case as it would break the formulas if you removed special characters. – kittycat Mar 03 '13 at 16:57
  • I just show the possibilities and I also warn for the consequences. It is possible but dangerous. Maybe it is an script to process formulas only used by the user. – automaticoo Mar 03 '13 at 17:04
  • The script is only for formulas, no need to worry about security. The example of automaticoo not work. – Karra Max Mar 03 '13 at 17:20
  • @Karra who will have access to the script and will it be publicly accessible? Anyone who can enter in data can run arbitrary commands on the server and thus hack your site/server. – kittycat Mar 03 '13 at 17:24
  • 1
    No, this is a scritp school work will only be performed off-line. – Karra Max Mar 03 '13 at 17:30