eval

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

evalBir dizgeyi bir PHP kodu olarak yorumlar

Açıklama

eval(string $kod_dizgesi): mixed

kod_dizgesi ile belirtilen dizgeyi bir PHP kodu olarak yorumlar.

Dikkat

eval() dil yapısı çok tehlikelidir çünkü keyfi PHP kodunun çalıştırılmasına izin verir. Bu nedenle kullanımı önerilmez. Bu yapıyı kullanmaktan başka bir seçeneğin olmadığına dikkatlice karar verilirse, önceden düzgün bir şekilde doğrulamadan kullanıcı tarafından sağlanan herhangi bir veriyi bu işleve aktarmamaya özellikle dikkat edilmelidir.

Bağımsız Değişkenler

kod_dizgesi

Yorumlanacak PHP kodlarını içeren dizge.

Dizge içindeki bir return deyimi dizgenin yorumlanmasını, anında durdurur.

Kod, PHP açılış ve kapanış PHP etiketleri ile sarmalanmaMAlıdır, yani '<?php echo "Merhaba!"; ?>' dizgesi yerine 'echo "Merhaba!";' dizgesi aktarılmalıdır. Uygun PHP etiketlerini kullanarak PHP kipinden çıkmak ve yeniden girmek hala mümkündür, örn. 'echo "PHP kipindeyiz!"; ?>HTML kipindeyiz! <?php echo "Tekrar PHP kipindeyiz!";'.

Bunun dışında aktarılan kod geçerli PHP kodu olmalıdır. Bu, tüm ifadelerin noktalı virgül kullanılarak uygun şekilde sonlandırılması gerektiği anlamına gelir. Örneğin 'echo "Merhaba!"' bir ayrıştırma hatasına sebep olurken, 'echo "Merhaba!";' çalışacaktır.

Bir return deyimi kodun yorumlanmasını derhal sonlandıracaktır.

Kod, eval() işlevini çağıran kodun etki alanında çalıştırılacaktır. Bu nedenle eval() çağrısında tanımlanan veya değiştirilen tüm değişkenler, işlev sonlandırıldıktan sonra görünür kalacaktır.

Dönen Değerler

Kod dizgesi içinde bir return bulunmadıkça eval() daima null döndürür. return ile bir değer döndürülmesi durumunda bu değeri döndürür. Belirtilen dizgede bir çözümleme hatası saptanırsa eval() PHP 7 öncesinde false döndürüp çalışma dosyadaki sonraki deyimden normal olarak devam eder; PHP 7 ve sonrasında ise ParseError istisnası yavrulanır. eval() işlevinin yorumladığı kodlardaki bir hatayı set_error_handler() kullanarak döndürmek mümkün değildir.

Örnekler

Örnek 1 - eval() örneği

<?php
$dizge
= 'Gülhane';
$isim = 'çınar';
$metin = 'Burası $dizge parkı ve ben bir $isim ağacıyım.';
echo
$metin. "\n";
eval(
"\$metin = \"$metin\";");
echo
$metin. "\n";
?>

Yukarıdaki örneğin çıktısı:

Burası $dizge parkı ve ben bir $isim ağacıyım.
Burası Gülhane parkı ve ben bir çınar ağacıyım.

Notlar

Bilginize: Bu bir işlev değil, dil oluşumu olduğundan değişken işlevler veya isimli bağımsız değişkenler kullanılarak çağrılamaz.

İpucu

Sonuçlarını doğrudan tarayıcıya çıktılayan her şey gibi, çıktı denetleme işlevleri bu işlevin de çıktısını yakalamak ve (örneğin) string türünde saklamak için kullanılabilir.

Bilginize:

Yorumlanan kodda ölümcül bir hata varsa betiğin tamamı durdurulur.

Ayrıca Bakınız

  • call_user_func() - İlk bağımsız değişkende belirtilen kullanıcı işlevini çağırır

add a note add a note

User Contributed Notes 16 notes

up
389
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
3
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
17
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
35
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
5
catgirl at charuru dot moe
6 years ago
It should be noted that imported namespaces are not available in eval.
up
22
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
4
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
5
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
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
2
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
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
1
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
0
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
-8
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!
up
-11
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
joseph at josephcz dot xyz
3 years ago
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.
To Top