How to handle parsing error for eval function in php

I am trying to use the eval function for php. but I am stuck in handling parsing errors. for example, if I have edge cases like 1 .. or 1 ++ if gives me a parsing error: syntax error, .....

Does anyone know how to handle a syntax error or how to get around an error message? I want to give a better error message.

Is it also possible to save a variable error message?

TIA

+1
source share
3 answers
$response = @eval($string); if (error_get_last()){ echo 'Show your custom error message'; //Or you can print_r(error_get_last()); } 
+11
source

From manual

Starting with PHP 7, if there is a parsing error in the evaluated code, eval() throws a ParseError exception. Prior to PHP 7, in this case, eval() returned FALSE , and the execution of the following code continued normally. Unable to catch parsing error in eval() with set_error_handler() .

Use this instead:

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

From manual :

If there is a parsing error in the evaluated code, eval() returns FALSE , and the execution of the following code continues normally. Unable to catch parsing error in eval() with set_error_handler() .

But as you will not call eval to arbitrary code (right?), This should not be a problem.

+2
source

Source: https://habr.com/ru/post/948035/


All Articles