PHP 8.3.7 Released!

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

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