0

I'm doing a logic validation like

$answer = eval("return ".$stringToValidate.";"); 

where $stringToValidate is a logic expression like 'a' == 'b' or 100 < 200.

The problem is when I introduce a invalid string like a == 'b' or 100 <<< 200.

I´m looking for a replacement for eval function or try-catch syntax error

I was trying using try catch like

try{
    $answer = eval("return ".$stringToValidate.";");
}catch(Exception $e){
    return $e->getMessage();
}

but didn't work

i expect the output true and false of eval function and a exception control for syntax error

EDIT:

i tryed the solutions of duplicated and have the same problem, using the try-catch or the function PHP eval and capturing errors (as much as possible)

specifically if use a expresion 10000 < 20000 < 30000 and get the textual error syntax error, unexpected '<' i investigate the symfony expresion language tool https://symfony.com/doc/current/components/expression_language.html but when the expresion fails here, throw false and i cannot diference a bad expresion and a expresion that was false

EDIT2: parse errors cannot be catched http://php.net/manual/en/function.set-error-handler.php

1 Answers1

1

If you use PHP 7, you can use ParserError :

error_reporting(E_ALL);

$stringToValidate = "'a == 'b'";

try {
    $answer = eval("return ".$stringToValidate.";");
} catch(Exception $e){
    return $e->getMessage();
} catch (ParseError $e) {
    echo 'Bad request !';
}

Edit : see cmbuckley comment

Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84