Reputation: 2257
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
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
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
Reputation: 31647
echo 'd41d8cd98f00b204e9800998ecf8427e';
.Alternatively, use the Parsekit.
Upvotes: 1