0

In mm project i want to evaluate mathematical formula which is a string. Example: "((1*10)/100) + 100".

How can evaluate such formula? I used eval() but it is throwing Parse error: syntax error, unexpected end of file error and eval is not a safe function to use.

Is that anyway if i can do that? And if there is no way except eval then how should i do it? Why it thrown Parse error: syntax error, unexpected end of file error?

Bhaskar Dabhi
  • 841
  • 1
  • 11
  • 28
  • `exec()` allows to execute commands, not to compute the result of a mathematical equation. That is something completely different. That string does not contain any commands, so no valid syntax. – arkascha Sep 28 '16 at 10:19

2 Answers2

0

php's exec() function allows to execute commands, not to compute the result of a mathematical equation or formula. That is something completely different. That string does not contain any commands, so it is not valid syntax.

Instead you need to feed a valid command into your call to exec() instead of a mathematical formula:

Have a look at this simple example:

<?php
$input = '((1*10)/100) + 100';
echo exec('php -r "echo ' . $input . ';"');

This obviously requires a command line version of php being available as php in case you try to trigger that from within a http server. But the same certainly can be done using any other available interpreter, for example bash.

An "inline" alternative (so without forking an external process) is to use php's eval() function. But again you need to feed it a command, not a formula. The advantage is that you do not have to rely on any other tool or interpreter to be usable at run time. The corresponding example would be:

<?php
$input = '((1*10)/100) + 100';
echo eval('return ' . $input . ';');

The output of both snippets obviously is 100.1.

Note however that it is crucial for both approaches to have complete control over what formula you feed into the execution. Do not allow client side input to pass into this unfiltered! That would allow any attacker to execute arbitrary code on your system!

arkascha
  • 41,620
  • 7
  • 58
  • 90
0

This will help you

echo eval('return '. "((1*10)/100) + 100" .';');
Jerald
  • 335
  • 1
  • 10