- Как узнать текст выражения, на котором eval() закончился с фатальной ошибкой?
- eval
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 20 notes
- ParseError
- Class synopsis
- User Contributed Notes 2 notes
- Parse error in template.php: eval()’d code
- Understanding the Error
- Locating the Error
- Repairing the Cause of the Error
Как узнать текст выражения, на котором 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» ;
?>?php
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
*/
?php
/*
* 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 ‘