Dan Q
Dan Q

Reputation: 2257

handling php eval syntax error for mathematic equations

suppose I do this in php:


eval("\$answer=1--1;");

The expression 1--1 will lead to a syntax error in eval, my question is how do I detect the error and handle it gracefully? ie: catch error in eval and then print out a helpful message. Right now, it just spits out "Parse error: syntax error, unexpected T_DEC". Unfortunately, the php manual states that it is not possible to catch parse errors with the set_error_handler() function.

This is for a simple school assignment and they have suggested using "eval()". As the assignment is trivial, perhaps there is no need to worry about these rare cases.

Upvotes: 0

Views: 2316

Answers (3)

bob-the-destroyer
bob-the-destroyer

Reputation: 3154

By pre-pending @ symbol to eval to suppress the error output, and then by checking error_get_last():

$test = @eval($str);
if (error_get_last())
    var_dump(error_get_last());

Then, parse the PHP token referenced in the error message ('message' value, or T_DEC in your case) against the list: http://php.net/manual/en/tokens.php

However, certain parse errors may fail your entire script, such as calling undefined functions. And, because you suppressed the error output, the failure won't appear in your logs. Basically: avoid eval for anything other than an amusing toy to pass the time.

Edit: I was going by the assumption "\$answer=1--1;" is not really the value you want to check (just too obvious), but just a test example of what kinds of strings you might be passing to eval. If it is really, you should just fix it right there. But if you want to pass and check any string at all in eval, then the above will help.

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157872

There are not a single reason to use eval for math equations.
As there are thousands math parsers around. Safe and maintainable.

Upvotes: 1

Oswald
Oswald

Reputation: 31647

  1. Prepend the string with something like echo 'd41d8cd98f00b204e9800998ecf8427e';.
  2. Turn on output buffering.
  3. eval
  4. Get contents of the output buffer and delete it.
  5. Test whether the contents start with 'd41d8cd98f00b204e9800998ecf8427e'.

Alternatively, use the Parsekit.

Upvotes: 1

Related Questions