PHP 8.3.7 Released!

eval

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

eval文字列を PHP コードとして評価する

説明

eval(string $code): mixed

指定した code を PHP コードとして評価します。

評価されるコードは、eval() がコールされた行における 変数のスコープ を継承します。コールされた時点で利用可能なあらゆる変数が、 評価されるコード中で読み取ることができますし、変更することもできます。 しかし、定義されている全ての関数やクラスは、グローバル名前空間で定義されます。 言い換えると、コンパイラは評価されるコードを include された別のファイルのようにみなすということです。

警告

eval()非常に危険な言語構造です。 というのも、任意の PHP コードを実行できてしまうからです。 これを使うことはおすすめしません。 いろいろ検討した結果どうしても使わざるを得なくなった場合は、細心の注意を払って使いましょう。 ユーザーから受け取ったデータをそのまま渡してはいけません。 渡す前に、適切な検証が必要です。

パラメータ

code

有効な PHP コード。これを評価します。

PHP 開始タグを含めてはいけません。つまり、 '<?php echo "Hi!"; ?>' ではなく 'echo "Hi!";' を渡さなければならないということです。 適切に PHP タグを使えば、PHP モードからいったん抜けてもう一度 PHP モードに戻るということも可能です。 たとえば、このようになります。 'echo "PHP モード!"; ?>HTML モード!<?php echo "ふたたび PHP モード!";'

それはさておき、渡すコードは PHP として有効な形式でなければなりません。 つまり、すべての文はセミコロンで終了する必要があるということです。 たとえば 'echo "やあ!"' はパースエラーになりますが、 'echo "やあ!";' は動作します。

return 文は、コードの評価をただちに終了します。

コードの実行は、eval() を呼び出したスコープ内で行われます。 したがって、eval() の中で定義したり変更したりした変数は eval() を抜けた後でも参照可能です。

戻り値

評価されるコードの中で return が コールされない限り、eval()null を返します。 return がコールされた場合は、その値を返します。 PHP 7 以降、評価されるコードの中でパースエラーが発生した場合は、 eval() は ParseError 例外をスローします。 PHP 7 より前のバージョンでは、この場合に eval()false を返していました。 それ以降のコードは通常通り実行されます。 eval() の中でのパースエラーを set_error_handler() で捕捉することはできません。

例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.

注意

注意: これは、関数ではなく 言語構造のため、可変関数名前付き引数 を用いてコールすることはできません。

ヒント

ブラウザに直接結果を出力する すべてのものと同様に、出力制御関数 を使用してこの関数の出力をキャプチャーし、(例えば)文字列 (string)に保存することが可能です。

注意:

評価されるコードの中で致命的なエラーが発生した場合は、 スクリプト全体が終了します。

参考

  • call_user_func() - 最初の引数で指定したコールバック関数をコールする

add a note

User Contributed Notes 7 notes

up
468
Anonymous
19 years ago
Kepp the following Quote in mind:

If eval() is the answer, you're almost certainly asking the
wrong question. -- Rasmus Lerdorf, BDFL of PHP
up
43
lord dot dracon at gmail dot com
8 years ago
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!\\\";\');\");');");
?>
up
22
Jeremie LEGRAND
6 years ago
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.
up
8
catgirl at charuru dot moe
6 years ago
It should be noted that imported namespaces are not available in eval.
up
24
bohwaz
12 years ago
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.
up
3
divinity76 at gmail dot com
6 years ago
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
up
6
darkhogg (foo) gmail (bar) com
14 years ago
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 ' );
?>
To Top