how to handle parse error for eval function in php

☆樱花仙子☆ 提交于 2019-12-01 20:29:15

问题


I'm trying to use the eval function for php. but I'm stuck in handling the parse error. like considering if I have edge cases like 1.. or 1++ if gives me parse error:syntax error, .....

anyone knows how to handle syntax error or how to bypass the error message? I want to give a better error message.

also is it possible to store the error message to a variable?

TIA


回答1:


From the manual

As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned FALSE and execution of the following code continued normally. It is not possible to catch a parse error in eval() using set_error_handler().

Instead use this:

<?php

try {
    eval('will cause error');
} catch (ParseError $e) {
    echo 'Caught exception: '.$e->getMessage()."\n";
}

https://3v4l.org/1giOS




回答2:


$response = @eval($string);
if (error_get_last()){
    echo 'Show your custom error message';
    //Or you can 
    print_r(error_get_last());
}



回答3:


From the manual:

If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().

But as you won't be calling eval on arbitrary code (right?), this shouldn't be a problem.



来源:https://stackoverflow.com/questions/10085284/how-to-handle-parse-error-for-eval-function-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!