0

Using code in codeigniter, php:

class test extends CI_Controller {
    public function index(){
        eval( '$amt = (' . $arithmetic_formula . ');' );
    }
}

getting error:

Warning Message: Division by zero

The variable $arithmetic_formula is a dynamic formula which can be change by the user anytime. And sometime we are having zero in the formula in which we don't have any control, that's why we are getting the error.

How can I deal with the above error, please help if anyone knows.

Thanks in advance !

rg007891
  • 53
  • 2
  • 12
  • 2
    The error says it all, you need to parse the `$arithmetic_formula` string serching for that division. Btw using eval is not a good idead for security reasons – Claudio Feb 19 '18 at 10:50
  • Love a bit of eval on a monday. Just check that the value before division isn't 0.. – IsThisJavascript Feb 19 '18 at 10:50
  • 1
    Eval is Evil ! Why don't you use a return instead ? anyway, you can use an If statement or a Try catch to fix this. – teeyo Feb 19 '18 at 10:50
  • 1
    What @teeyo say's, try/catch the eval function and check value's before using them. – Wouter Veen Feb 19 '18 at 10:54
  • If you insist on using `eval` go ahead an use a `try-catch` clause. – Tobias F. Feb 19 '18 at 10:57
  • Use try and catch for this – Danish Ali Feb 19 '18 at 12:31
  • @Nigel Ren I have seen the post on which behalf you have marked my question as duplicate but As I can see that post I am not getting the answer from there. – rg007891 Feb 19 '18 at 12:55
  • @claudio The `$arithmetic_formula` is dynamic and can have any number of brackets and arithmetic operators and including some defined variables. And this make it more difficult to parse it. Example Original Formula: `($a + $b) - ($c + $d) / ($e * $f) ` After value evaluated: `(1 + 2) - (3 + 4 ) / (5 * 0) ` – rg007891 Feb 19 '18 at 13:13
  • 1
    @teeyo try catch is not working with eval() – rg007891 Feb 19 '18 at 13:14
  • @RohitGusain you're right, I didn't know that ... just another reason not use eval :) – teeyo Feb 19 '18 at 16:08
  • Pop an @ symbol in front of eval and you'll be good to go ;) – Alex Feb 19 '18 at 18:29

0 Answers0