eval

(PHP 4, PHP 5, PHP 7, PHP 8)

eval把字符串作为PHP代码执行

说明

eval ( string $code ) : mixed

把字符串 code 作为PHP代码执行。

Caution

函数eval()语言结构是 非常危险的, 因为它允许执行任意 PHP 代码。 它这样用是很危险的。 如果您仔细的确认过,除了使用此结构以外 别无方法, 请多加注意,不要允许传入任何由用户 提供的、未经完整验证过的数据

参数

code

需要被执行的字符串

代码不能包含打开/关闭 PHP tags。比如, 'echo "Hi!";' 不能这样传入: '<?php echo "Hi!"; ?>'。但仍然可以用合适的 PHP tag 来离开、重新进入 PHP 模式。比如 'echo "In PHP mode!"; ?>In HTML mode!<?php echo "Back in PHP mode!";'

除此之外,传入的必须是有效的 PHP 代码。所有的语句必须以分号结尾。比如 'echo "Hi!"' 会导致一个 parse error,而 'echo "Hi!";' 则会正常运行。

return 语句会立即中止当前字符串的执行。

代码执行的作用域是调用 eval() 处的作用域。因此,eval() 里任何的变量定义、修改,都会在函数结束后被保留。

返回值

eval() 返回 null,除非在执行的代码中 return 了一个值,函数返回传递给 return 的值。 PHP 7 开始,执行的代码里如果有一个 parse error,eval() 会抛出 ParseError 异常。在 PHP 7 之前, 如果在执行的代码中有 parse error,eval() 返回 false,之后的代码将正常执行。无法使用 set_error_handler() 捕获 eval() 中的解析错误。

范例

Example #1 eval() 例子 - 简单的文本合并

<?php
$string 
'cup';
$name 'coffee';
$str 'This is a $string with my $name in it.';
echo 
$str"\n";
eval(
"\$str = \"$str\";");
echo 
$str"\n";
?>

以上例程会输出:

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

注释

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

Tip

和直接将结果输出到浏览器一样,可使用输出控制函数来捕获当前函数的输出,然后(例如)保存到一个 string 中。

Note:

如果在执行的代码中产生了一个致命的错误(fatal error),整个脚本会退出。

参见

User Contributed Notes

remindfwd 09-Jan-2021 05:30
Note that

<?php

echo eval( '$var = (20 - 5);' );  // don't show anything

echo ' someString ' . eval( 'echo $var = 15;' ); // outputs 15 someString

//or
echo ' someString ' . eval( 'echo $var = 15;' ) . ' otherString '; // 15 someString  otherString 

//or
echo ' someString ' . eval( 'echo $var = 15;' ) . ' otherString ' . '...' .eval( 'echo " __ " . $var = 10;' ); // 15 __ 10 someString  otherString  ...

?>
joseph at josephcz dot xyz 29-Mar-2020 02:42
In 2020, many people don't want to mix their PHP code and HTML, and they also think PHP itself is better than any template engines. But whenever you are making an template engine, use "include" to include your view file instead of using eval(). Many farmeworks are using this solution, such as Laravel.

If you rally want to eval a string, write them to a cached .php file first, then include it.
catgirl at charuru dot moe 17-Dec-2017 11:49
It should be noted that imported namespaces are not available in eval.
solobot 07-Nov-2017 09:55
eval() is workaround for generating multiple anonymous classes with static properties in loop

public function generateClassMap()
    {
        foreach ($this->classMap as $tableName => $class)
        {
            $c = null;
            eval('$c = new class extends \common\MyStaticClass {
                public static $tableName;
                public static function tableName()
                {
                    return static::$tableName;
                }
            };');
            $c::$tableName = $this->replicationPrefix.$tableName;
            $this->classMap[$tableName] = $c;

        }
    }

thus every class will have its own $tableName instead of common ancestor.
Jeremie LEGRAND 28-Jun-2017 03:25
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.
divinity76 at gmail dot com 06-Jun-2017 09:35
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
Uther 02-Feb-2016 05:33
eval'd code within namespaces which contain class and/or function definitions will be defined in the global namespace... not incredibly obvious :/
lord dot dracon at gmail dot com 31-Jul-2015 01:46
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!\\\";\');\");');");
?>
Karel 03-Feb-2015 04:23
For them who are facing syntax error when try execute code in eval,


<?php

$str
'<?php echo "test"; ?>';

eval(
'?>'.$str.'<?php;'); // outputs test
eval('?>'.$str.'<?'); // outputs test
eval('?>'.$str.'<?php');// throws syntax error - unexpected $end

?>
bohwaz 04-Feb-2012 10:51
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.
php at rijkvanwel dot nl 13-Sep-2010 07:41
To catch a parse error in eval()'ed code with a custom error handler, use error_get_last() (PHP >= 5.2.0).

<?php
$return
= eval( 'parse error' );

if (
$return === false && ( $error = error_get_last() ) ) {
   
myErrorHandler( $error['type'], $error['message'], $error['file'], $error['line'], null );

   
// Since the "execution of the following code continues normally", as stated in the manual,
    // we still have to exit explicitly in case of an error
   
exit;
}
?>
darkhogg (foo) gmail (bar) com 30-Mar-2010 10:33
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 ' );
?>
php at stock-consulting dot com 28-Nov-2008 08:16
Magic constants like __FILE__ may not return what you expect if used inside eval()'d code. Instead, it'll answer something like "c:\directory\filename.php(123) : eval()'d code" (under Windows, obviously, checked with PHP5.2.6) - which can still be processed with a function like preg_replace to receive the filename of the file containing the eval().

Example:

<?php
$filename
= preg_replace('@\(.*\(.*$@', '', __FILE__);
echo
$filename;
?>
marco at harddisk dot is-a-geek dot org 30-Jun-2008 10:44
eval does not work reliably in conjunction with global, at least not in the cygwin port version.

So:
<?PHP
class foo {
 
//my class...
}
function
load_module($module) {
  eval(
"global \$".$module."_var;");
  eval(
"\$".$module."_var=&new foo();");
 
//various stuff ... ...
}
load_module("foo");
?>

becomes to working:

<?PHP
class foo {
 
//my class...
}
function
load_module($module) {
  eval(
'$GLOBALS["'.$module.'_var"]=&new foo();');
 
//various stuff ... ...
}
load_module("foo");
?>

Note in the 2nd example, you _always_ need to use $GLOBALS[$module] to access the variable!
Ipseno at yahoo dot com 25-Feb-2008 10:24
If you attempt to call a user defined function in eval() and .php files are obfuscated by Zend encoder, it will result in a fatal error.

Use a call_user_func() inside eval() to call your personal hand made functions.

This is user function
<?php

function square_it($nmb)
{
    return
$nmb * $nmb;
}

?>

//Checking if eval sees it?
<?php

$code
= var_export( function_exists('square_it') );

eval(
$code );    //returns TRUE - so yes it does!

?>

This will result in a fatal error:
PHP Fatal error:  Call to undefined function square_it()
<?php

$code
= 'echo square_it(55);' ;

eval(
$code );

?>

This will work
<?php

$code
= 'echo call_user_func(\'square_it\', 55);' ;

eval(
$code );

?>
12-Jul-2004 09:37
Kepp the following Quote in mind:

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