CakeFest 2024: The Official CakePHP Conference

eval

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

evalWertet eine Zeichenkette als PHP-Code aus

Beschreibung

eval(string $code): mixed

Wertet die in code enthaltene Zeichenkette als PHP aus.

Der ausgewertete Code erbt den Geltungsbereich der Variablen von der Zeile, in der die Funktion eval() aufgerufen wird. Alle Variablen, die in dieser Zeile verfügbar sind, können im ausgewerteten Code gelesen und verändert werden. Alle definierten Funktionen und Klassen werden jedoch im globalen Namensraum definiert. Mit anderen Worten, der Compiler betrachtet den ausgewerteten Code so, als wäre er eine separate eingebundene Datei.

Achtung

Das eval()-Sprachkonstrukt ist sehr gefährlich, weil es die Ausführung von beliebigem PHP-Code erlaubt. Seine Verwendung wird daher nicht empfohlen. Wenn sorgfältig überprüft wurde, dass es keine andere Möglichkeit gibt als dieses Konstrukt zu verwenden, ist besonders darauf zu achten keine von Nutzern bereit gestellten Daten zu übergeben ohne diese zuvor ordnungsgemäß zu validieren.

Parameter-Liste

code

Gültiger PHP-Code, der ausgewertet werden soll.

Der Code darf nicht in öffnende und schließende PHP-Tags eingeschlossen sein, d. h. 'echo "Hi!";' muss anstelle von '<?php echo "Hi!"; ?>' übergeben werden. Es ist dennoch möglich den PHP-Modus durch die entsprechenden PHP-Tags zu verlassen und wieder zu betreten, z. B. 'echo "Im PHP-Modus!"; ?>Im HTML-Modus!<?php echo "Wieder im PHP-Modus!";'.

Abgesehen davon muss der übergebene Code gültiges PHP sein. Das beinhaltet, dass alle Anweisungen ordnungsgemäß mit einem Strichpunkt terminiert sein müssen. 'echo "Hi!"', zum Beispiel, verursacht einen Parse-Fehler, wohingegen 'echo "Hi!";' funktioniert.

Eine return-Anweisung beendet die Auswertung des Codes sofort.

Der Code wird im Geltungsbereich des eval() aufrufenden Codes ausgeführt. Daher bleiben sämtliche Variablen, die im eval() Aufruf definiert oder geändert werden, nach dessen Ende sichtbar.

Rückgabewerte

eval() gibt null zurück, außer wenn im ausgewerteten Code return aufgerufen wird, dann aber wird der an return übergebene Wert zurückgegeben. Von PHP 7 an, wird eval() im Falle eines Parse Errors im ausgewerteten Code eine ParseError Exception werfen. Vor PHP 7 gab eval() in diesem Fall false zurück und der weitere Code wurde normal ausgeführt. Es ist in eval() nicht möglich, einen Parse Error mittels set_error_handler() abzufangen.

Beispiele

Beispiel #1 eval()-Beispiel (einfache Texteinfügung)

<?php
$string
= 'Bierglas';
$name = 'Binding-Lager';
$str = 'Das ist mein $string, voll mit $name.';
echo
$str . "\n";
eval (
"\$str = \"$str\";");
echo
$str . "\n";
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Das ist mein $string, voll mit $name.
Das ist mein Bierglas, voll mit Binding-Lager.

Anmerkungen

Hinweis: Da dies ein Sprachkonstrukt und keine Funktion ist, können Sie dieses nicht mit Variablenfunktionen oder benannten Parametern verwenden.

Tipp

Bei allem, dessen Ergebnisausgabe direkt im Browser angezeigt wird, können Sie die Funktionen zur Ausgabesteuerung verwenden. Damit lässt sich die Ausgabe dieser Funktion erfassen, und - zum Beispiel - in einem string speichern.

Hinweis:

Im Fall eines schweren Fehlers im augewerteten Code wird das komplette Skript beendet.

Siehe auch

  • call_user_func() - Ruft die Callback-Funktion auf, die als erster Parameter übergeben wurde

add a note

User Contributed Notes 20 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
42
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
23
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
7
catgirl at charuru dot moe
6 years ago
It should be noted that imported namespaces are not available in eval.
up
6
darkhogg (foo) gmail (bar) com
13 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 ' );
?>
up
1
remindfwd
3 years ago
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 ...

?>
up
2
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
0
xxixxek at gmail dot com
1 year ago
I happened to work on a very old code that, for many reasons, couldn't be rewritten and the only way of showing the exact error in eval that worked for me was:

$res = eval($somecode);

if(!$res) {
echo "<pre>";
print_r(explode(PHP_EOL, $somecode));
echo "</pre>";
}

I know it is terrible but I didn't have much of a choice. None of the try...catch solutions worked for me; the solution above shows the exact lines with numbers and it is easy to find what's wrong with the code.
up
-1
xxixxek at gmail dot com
1 year ago
I happened to work on a very old code that, for many reasons, couldn't be rewritten and the only way of showing the exact error in eval that worked for me was:

$res = eval($somecode);

if(!$res) {
echo "<pre>";
print_r(explode(PHP_EOL, $somecode));
echo "</pre>";
}

I know it is terrible but I didn't have much of a choice. None of the try...catch solutions worked for me; the solution above shows the exact lines with numbers and it is easy to find what's wrong with the code.
up
0
stocki dot r at gmail dot com
2 years ago
You can use `eval()` to combine classes/traits dynamically with anonymus classes:

<?php

function init($trait, $class) {
return (
trait_exists($trait) && class_exists($class))
? eval(
"return new class() extends {$class} { use {$trait}; };")
:
false;
}

trait
Edit {
function
hello() { echo 'EDIT: ' . $this->modulename; }
}
trait
Ajax {
function
hello() { echo 'AJAX: ' . $this->modulename; }
}
class
MyModule {
public
$modulename = 'My Module';
}
class
AnotherModule {
public
$modulename = 'Another Module';
}

init('Edit', 'MyModule')->hello(); # 'EDIT: My Module'
init('Ajax', 'AnotherModule')->hello(); # 'AJAX: Another Module'

?>
up
1
Karel
9 years ago
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

?>
up
0
solobot
6 years ago
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.
up
0
php at rijkvanwel dot nl
13 years ago
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;
}
?>
up
-1
Uther
8 years ago
eval'd code within namespaces which contain class and/or function definitions will be defined in the global namespace... not incredibly obvious :/
up
-2
php at stock-consulting dot com
15 years ago
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;
?>
up
-1
greald at gmail dot com
2 years ago
to avoid the evil eval() you may use the fact that function names, variable names, property names and method names can be handled strings.

<?php
class Fruit
{
public
$tomato = "Tomatos";

public function
red() {return " are red. ";}
}

$fruit = new Fruit;
$fruitStr = "tomato";
$colorStr = "red";

echo
$fruit->$fruitStr . $fruit->$colorStr();

// and procedural //////////////////////////////////////////

$lemon = "Lemons";

function
yellow() {return " are yellow. ";}

$fruitStr = "$lemon";
$colorStr = "yellow";

echo
$fruitStr . $colorStr();
?>
up
-2
Patanjali
1 year ago
eval() is useful for preprocessing css (and js) with php to embed directly into a style tag in the head tag (or script tag at the bottom of body tag) of the HTML of the page.

This:

a. Prevents Flash of White in Chrome or Firefox (where an external css file arrives briefly too late to render the HTML).

b. Allows radical minifying by testing the page source to see if whole blocks of rules or code are even required, such as for tables.

c. Allows custom source-content-dependent css rules to be created on the fly. (I use this to create rules for positioned labels over an image that scale with it)

d. Allows generation of a hash of the processed css or js for use in the page's CSP header for style-src or script-src to prevent injection attacks.

Here eval() is safe because it is not using user-supplied (person or browser) information
up
-13
Ipseno at yahoo dot com
16 years ago
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 );

?>
up
-11
marco at harddisk dot is-a-geek dot org
15 years ago
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!
To Top