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

5
  • a == 'b' generates a warning, not an exception, when I try it. 100 <<< 200 generates a parse error, which you can't catch. Commented Jan 2, 2019 at 14:49
  • A better duplicate: PHP eval and capturing errors (as much as possible) - TL;DR use PHP7 and catch ParseError. Commented Jan 2, 2019 at 14:50
  • @cmbuckley Cheers, I've added that to the dupes list. Commented Jan 2, 2019 at 14:52
  • Thanks, I've just noticed the link to do that myself in future ;-) Commented Jan 2, 2019 at 14:54
  • @ceejayoz exist any form of capturing that parse error? Commented Jan 2, 2019 at 16:30

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.