Php parse error eval code

Как узнать текст выражения, на котором eval() закончился с фатальной ошибкой?

В коде используем eval для вычисления значения формул. В случае злостной ошибки в тексте выражения PHP фатально ошибается и всё, что остаётся в логах:

PHP Fatal Error: syntax error, unexpected ')' in Form/Validate/DinamicFormulaValues.php(149) : eval()'d code on line 1

Как вывести в консоль текст выражения, которое не удалось проевалить?

У меня в голове такой вариант:

$expression = "1 + 2)"; // тут явно похожая синтаксическая ошибка - незакрытая скобка $file = tempnam('/tmp', 'eval') file_put_contents($file, ";"); $value = include($file);

После этого возникает ошибка

Parse error: syntax error, unexpected ')' in /tmp/eval1kGtG7 on line 1

(при должной сноровке и чуточке разума это сообщение уходит почтой админу или разработчикам)

Открываю файл /tmp/eval1kGtG7 и вижу синтаксическую ошибку

$result = exec('php -l "'.$file.'"', $output); // это консольная команда проверки синтаксиса файла PHP echo $result; // -> Errors parsing /tmp/eval1kGtG7 echo implode("\n", $output); // -> PHP Parse error: syntax error, unexpected ')' in /tmp/eval1kGtG7 on line 1

Мне не нравится то, что файлов будет не просто много, а очень очень много, потому что через эту конструкцию проходит сотни проверок.

Недостаток этого варианта: в error_get_last() остаётся результат от интерпретации предыдущего неудачного выражения, а проверок будет сотни — получается, что будет много ложных срабатываний на рекорректность.

Оценить 4 комментария

Источник

eval

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Parameters

Valid PHP code to be evaluated.

The code must not be wrapped in opening and closing PHP tags, i.e. ‘echo «Hi!»;’ must be passed instead of » . It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags, e.g. ‘echo «In PHP mode!»; ?>In HTML mode!

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon. ‘echo «Hi!»‘ for example will cause a parse error, whereas ‘echo «Hi!»;’ will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval() . Thus any variables defined or changed in the eval() call will remain visible after it terminates.

Return Values

eval() returns null unless return is called in the evaluated code, in which case the value passed to return is returned. 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() .

Examples

Example #1 eval() example — simple text merge

$string = ‘cup’ ;
$name = ‘coffee’ ;
$str = ‘This is a $string with my $name in it.’ ;
echo $str . «\n» ;
eval( «\$str = \» $str \»;» );
echo $str . «\n» ;
?>

The above example will output:

This is a $string with my $name in it. This is a cup with my coffee in it.

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

Note:

In case of a fatal error in the evaluated code, the whole script exits.

See Also

User Contributed Notes 20 notes

Kepp the following Quote in mind:

If eval() is the answer, you’re almost certainly asking the
wrong question. — Rasmus Lerdorf, BDFL of PHP

At least in PHP 7.1+, eval() terminates the script if the evaluated code generate a fatal error. For example:
@eval( ‘$content = (100 — );’ );
?>

(Even if it is in the man, I’m note sure it acted like this in 5.6, but whatever)
To catch it, I had to do:
try eval( ‘$content = (100 — );’ );
> catch ( Throwable $t ) $content = null ;
>
?>

This is the only way I found to catch the error and hide the fact there was one.

Inception Start:
eval( «echo ‘Inception lvl 1. \n’; eval(‘echo \»Inception lvl 2. \n\»; eval(\»echo \’Inception lvl 3. \n\’; eval(\’echo \\\»Limbo!\\\»;\’);\»);’);» );
?>

Источник

ParseError

ParseError is thrown when an error occurs while parsing PHP code, such as when eval() is called.

Note: ParseError extends CompileError as of PHP 7.3.0. Formerly, it extended Error .

Class synopsis

User Contributed Notes 2 notes

The priority of Parse Error should be higher than that of Fatal Error,Parse Error, which has the highest priority among all PHP exceptions. See the following example:
error_reporting ( E_ALL );
test ()
//System output a parse error
?>
error_reporting ( E_WARNING );
test ()
//System output a parse error
?>
error_reporting ( E_ERROR );
test ()
//System output a parse error
?>
error_reporting ( E_PARSE );
test ()
//System output a parse error
?>

/*
* The function eval() evaluate his argument as an instruction PHP
* Then the argument must respect the standar of PHP codage
* In this example the semicolon are missign
*/

/*
* If you run this code the result is different of the result of above code
* PHP will output the standar parse Error: syntax error, .
*

  • Predefined Exceptions
    • Exception
    • ErrorException
    • Error
    • ArgumentCountError
    • ArithmeticError
    • AssertionError
    • DivisionByZeroError
    • CompileError
    • ParseError
    • TypeError
    • ValueError
    • UnhandledMatchError
    • FiberError

    Источник

    Parse error in template.php: eval()’d code

    There are a lot of hacks that include instructions for modifying template files. Since every template released can be very different from others and many people customize their installed templates, there are a lot of potential problems that can arise when applying a hack. One of them is an error message like this one:

    Parse error: parse error in /path/to/forum/includes/template.php(127) : eval()’d code on line XX

    Most people who see this error get very confused, because it seems to say that there is a parse error in template.php, but they have not recently altered this file. Before you can learn how to fix this error, you must first come to understand what it means.

    Understanding the Error

    The key to this error is the later part of the message: eval()’d code on line XX. By including this, the software is trying to tell you something specific about the problem that was encountered. It is saying that the cause of the error is not in template.php itself, but some code from another file that is being processed in template.php.

    To understand where this error originates, first you need to know something about how template.php works. A large part of this is reading .tpl template files in and storing the contents of those files in variables. The variables are then sent through compiling, a process which replaces template variables like with a value and adds special commands for displaying the page. After being compiled, the variables might contain something similar to this:

    echo ‘ ‘;
    echo ‘I am a phpBB page. or at least I will be!’;
    echo ‘All of this is PHP code that can be executed to print out the actual page.’;
    echo ‘‘;

    When a portion of phpBB sends text output to the browser, it does this by parsing a template. Parsing a template actually means that the variables created from a template file are evaluated — or eval()’d, as the error message says. So, the cause of the error is actually in one of the template files used by the page that displays the error.

    Locating the Error

    So how do you fix this error? Since the error message does not tell you which template file causes the problem, you need to check each file used by the page showing the error. The first step is to compile a list of all the template files the page uses. Here is a brief checklist that can narrow the suspects down considerably.

    1. Has the error started to appear after editing some template files? If so, one of those files causes the error.
    2. Does the error appear on every page of the forum? Only two template files are used on every single page. These are overall_header.tpl and overall_footer.tpl. Some modifications may add the use of extra template files; if so, these files should be mentioned by name
      somewhere in includes/page_header.php or includes/page_tail.php.
    3. Does the error appear in the Admin Panel? When this happens, one of the template files in the admin folder of your
      template is the cause. If the error is on every page of the Admin Panel,
      check page_header.tpl and page_footer.tpl, the Admin Panel versions of the overall template files.

    When this checklist doesn’t help you locate the file causing the problem, you will need to check through the .php file of the page displaying the error for names of template files. Look for the line below. Usually, there will be some nearby lines that name template files used by the page. This may happen in several places in the file, so be sure to check thoroughly.

    So now that you’ve found the template files that might contain the mistake, what is the actual problem in the file? This is where things can get difficult. There are several potential causes of the parse error. If you go back to the error message, you’ll see that it says eval()’d code on line XX, where XX is some line number. You may think that the mistake is on this line in the template file, but this is often not the case. The line number refers to the evaluated code, which can often have many more lines than the template file. You can’t rely on the line number in the error message, so instead you’ll have to look through the template file manually to find the problem.

    Repairing the Cause of the Error

    There are a few common errors that you might find while examining the template files. Let’s look at the errors that are found most often and how to fix them.

    First, check for badly formed template variables. Template variables are words, usually in all uppercase letters, surrounded by curly brackets, such as or . Sometimes, one of the curly brackets might be missing, resulting in something like or USERNAME>. That creates a parse error that can be fixed by adding the missing bracket.

    Template switches are another potential source of problems. Template switches are a special feature phpBB uses for loops and conditional display of page elements. They look like HTML comments, but have a few specific rules to separate the two. Here are some examples of template switches.

    This text is displayed only to logged out users.

    The postrow switch is a «loop switch.»
    Loop switches are used for displaying repeating
    blocks of content, like posts in topics.

    Earlier, I mentioned that template switches have certain rules that separate them from normal HTML comments. Breaking these rules results in parse errors, so you need to check your template file for any switches that do not follow the rules. As a side note, the eXtreme Styles modification loosens these rules and will prevent most parse errors caused by template switches.

    The first rule is, «Each opening and closing switch line must be on a line containing no other code.» Any of the example switch usages below would cause a parse error. Did you notice, in the example above, that each switch has a BEGIN line, one or more lines of content, and then an END line? That is the correct way to write a switch.

    Switch statements are case and space sensitive. This means they must begin with followed by exactly one space, the text BEGIN or END in all uppercase, exactly one space, a switch name containing allowed characters, exactly one space, and end with —>. Almost all characters other than spaces are allowed in switch names. It’s easy to leave out or add extra spaces; since switches look so much like HTML comments, they might still look valid to your eye. These are not valid switch statements, though:

    Missing space on the last line before END.

    Two spaces between BEGIN and bad_switch.

    Incomplete switches are another guaranteed problem. If a template file has the BEGIN line of a switch, but is missing the matching END line, then that will definitely cause a parse error. The reverse is also true: if there is an END line that doesn’t have a BEGIN line, that causes an error. The BEGIN line must also be placed before the END line.

    Switches can be nested, meaning that you can have switches inside other switches. When nested, switches must be closed in the same order that they were opened. The following example shows nested switches that are closed in the wrong order.

    Источник

  • Читайте также:  Задача четные элементы питон
Оцените статью