eval
(PHP 4, PHP 5)
eval — Evaluate a string as PHP code
Description
Evaluates the given code
as PHP.
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
-
code
-
Valid PHP code to be evaluated.
The code mustn't be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<? echo "Hi!"; >'. It is still possible to leave and reenter PHP mode though using the appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!<? echo "Back in PHP 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. If there is a
parse error in the evaluated code, eval() returns
FALSE
and execution of the following code continues normally. It is
not possible to catch a parse error in eval()
using set_error_handler().
Examples
Example #1 eval() example - simple text merge
<?php
$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.
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.
Коментарии
Kepp the following Quote in mind:
If eval() is the answer, you're almost certainly asking the
wrong question. -- Rasmus Lerdorf, BDFL of PHP
The following code
<?php
eval( '?> foo <?php' );
?>
does not throw any error, but prints the opening tag.
Adding a space after the open tag fixes it:
<?php
eval( '?> foo <?php ' );
?>
If you want to allow math input and make sure that the input is proper mathematics and not some hacking code, you can try this:
<?php
$test = '2+3*pi';
// Remove whitespaces
$test = preg_replace('/\s+/', '', $test);
$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+\/*\^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns
if (preg_match($regexp, $q))
{
$test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
eval('$result = '.$test.';');
}
else
{
$result = false;
}
?>
I can't guarantee you absolutely that this will block every possible malicious code nor that it will block malformed code, but that's better than the matheval function below which will allow malformed code like '2+2+' which will throw an error.
Inception with eval()
<pre>
Inception Start:
<?php
eval("echo 'Inception lvl 1...\n'; eval('echo \"Inception lvl 2...\n\"; eval(\"echo \'Inception lvl 3...\n\'; eval(\'echo \\\"Limbo!\\\";\');\");');");
?>
imo, this is a better eval replacement:
<?php
function betterEval($code) {
$tmp = tmpfile ();
$tmpf = stream_get_meta_data ( $tmp );
$tmpf = $tmpf ['uri'];
fwrite ( $tmp, $code );
$ret = include ($tmpf);
fclose ( $tmp );
return $ret;
}
?>
- why? betterEval follows normal php opening and closing tag conventions, there's no need to strip `<?php?>` from the source. and it always throws a ParseError if there was a parse error, instead of returning false (note: this was fixed for normal eval() in php 7.0). - and there's also something about exception backtraces
At least in PHP 7.1+, eval() terminates the script if the evaluated code generate a fatal error. For example:
<?php
@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:
<?php
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.
It should be noted that imported namespaces are not available in eval.