eval

(PHP 3, PHP 4, PHP 5)

eval -- Evaluate a string as PHP code

Description

mixed eval ( string code_str )

eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.

There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.

Also remember that variables given values under eval() will retain these values in the main script afterwards.

A return statement will terminate the evaluation of the string immediately. As of PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. In case of a parse error in the evaluated code, eval() returns FALSE. In case of a fatal error in the evaluated code, the whole script exits. In PHP 3, eval() does not return a value.

例子 1. eval() example - simple text merge

<?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 类型的变量中。

See also call_user_func().


add a note add a note User Contributed Notes
samme at vimio
03-Nov-2006 06:06
To Nova912

Your code really made me dizzy.
Never ever do something like.
<?php
$if_statement
= 'wierd && boolean == expression';
if (eval(
"return ".$if_statement.";")) {
 
do_stuff();
}
?>

but rather.

<?php
if (wierd && boolean == expression) {
 
do_stuff();
}
?>

Ok thanks bye.
Joeri
16-Oct-2006 02:07
This is a variation on the contribution of Matt's note, to load a php file into a variable and then evaluate it (which works perfect).

This snippet does almost te same, but instead of sending it back to the browser, it sends it back to a variable.

<?PHP
function phpWrapper($content) {
 
ob_start();
 
$content = str_replace('<'.'?php','<'.'?',$content);
 eval(
'?'.'>'.trim($content).'<'.'?');
 
$content = ob_get_contents();
 
ob_end_clean();
 return
$content;
}

$content = file_get_contents('feedback.php');
$content = phpWrapper($content);

// $content will now contain your evaluated code :)
?>
Dale Kern, Salt Lake City
11-Oct-2006 01:16
If you are trying to get eval()  to run a string as if it were from an include file, try this:

eval("?>".$string);

Eval starts in PHP Script mode, break into html mode first thing and you're done.
Nova912
22-Jul-2006 04:17
Well let me just start off by saying that eval(); confused the heck out of me untill I read that you can use Return.

This will help anyone who wants to "Inject" code into an IF statement. My example is a survey site, some questions are required, some are only required if others are checked. So let me share with you my dynamic script and show you how I was able to make a Dynamic IF Statement.

The code below had been altered to be understandable.
<?php
$survey_number
= 3 // The third survey. (Out of 10 Surveys)
$rq[3] = array(1,2,3,4,5,6,8,9,11,13,15,17,19,20); // Required Questions  for Survey 3 - Some of these can not be "NULL" (not NULL) or they will stop the script from going any further. (In my script I replaced any questions that were not answered with "NULL" using a for loop based on the number of questions in the survey)
$aa[3][4] = ' && '.$q[3].' == "1"'; // Added Arguments - 3 = Survey 3's Arguments, 4= Argument belongs to question 4, $q[1-20] (20 Questions total in this case.

//HERE IS THE DYNAMIC IF STATEMENT
$count = count($rq[$survey_number]);
   for (
$i=0;$i< $count;$i++)
       {
      
$if_statement = '$q['.$rq[$survey_number][$i].'] == "NULL"';
       if(isset(
$aa[$survey_number][$rq[$survey_number][$i]]))
           {
          
$if_statement .= $aa[$survey_number][$rq[$survey_number][$i]];
           }
       if(eval(
"return ".$if_statement.";"))
           {
           echo
$rq[$survey_number][$i].': Is NULL and IS NOT ok.<br>';
           }
       else
           {
           echo
$rq[$survey_number][$i].': Is NULL and IS ok.<br>';
           }
       }
?>

In my experiance with this the Added Argument needs to have an actual value inplanted into the string, it did not work by just putting $q[3], i had to use '.$q[3].' to place the value of question 3 in the string.

I hope this help someone, I spent so much time trying to figure this out and want to share how something this simple is done.

Thank you.
alerante at bellsouth dot net
09-Jul-2006 01:41
Regarding the problem posted by jkuckartz1984 at hotmail dot com: you must return a value in the eval'd code block, so the code really should be

<?php

if (eval("return \$total".$i.";")) {
   echo
"eval: total2 is full<br>";
} else {
   echo
"eval: total2 is empty<br>";
}

?>

However, this is really a job for "variable variables" < http://php.net/variables.variable >:

<?php

$varname
= "total$i";
if ($
$varname) {
   [...]
}

?>
brettz9 a/- yah00 do/- com
06-Jul-2006 05:19
I was trying to build a multidimensional array to an unknown dimension (within a loop or "while") and found that eval is, as far as I can tell, the only simple way to solve the problem.

<?php
$arr
= array(2,
                 array(
"v", "q", 5,
                                   array(
5, 8, "g"),
                                                    
"x"));
$i=3;
$key1 = "[1]";
$key2 = "[".$i."]"; // E.g., could build this conditionally within a loop
$key3 = "[2]";

$keys = $key1.$key2.$key3; // Can add as many keys as needed (could be done instead via a loop with repeated calls to .= )

print $arr{$keys}; // This does not work
print $arr[$keys]; // This also does not work

// However...
eval("\$value = \$arr{$keys};");
print
$value; // Correctly prints "g"
?>
burninleo at gmx dot net
25-May-2006 08:51
The only way to retreive information on parse errors in eval'd code seems to be the output buffering.

<?PHP
// Append a return true to php-code to check on errors
$code.= "\nreturn true;";
// Send any output to buffer
ob_start();
// Do eval()
$check = eval($code);
$output = ob_get_contents();
ob_end_clean();
// Send output or report errors
if ($check === true) {
  echo
$output;
} else {
 
// Manually parse output for errors and
  // generate usable information for the user
  // especially content of error-lines.
 
$pattern = '/^\s*Parse error\s*:(.+) in (.+) on line (\d+)\s*$/m';
 
etc ...
}
aoeuid at gmail dot com
15-May-2006 03:50
Just as a reply to 'evildictaitor', eval() obfuscation can be of use use against script kiddies, or people with little free time if implemented more intelligently.

And by more intelligently I mean more randomly, do perhaps a hundred iterations and randomly choose the obfuscation method every iteration. Doing rot13 with base64 once, then something from Mcrypt() and so on. Might take its toll on performance, but atleast isn't _that_ easily solved by eval->print :)

Of course, obfuscation isn't really a way to securing your code, but might work if one's in a hurry and doesn't have anything else better.
evildictaitor at hotmail dot com
02-Apr-2006 01:34
Don't use eval to obfruscate code. Don't. No. stop. Never. Ever. It's so incredibly easy to decode, it's not worth it.

<?php

  $someAwfulObfrsucatedCode
= "1209;nlu[qer;j12.n";
  function
someImpressiveDeobfruscationRoutine($string){
   ..
somecode..
   return
$realCode;
  }

  eval(
someImpressiveDeobfruscationRoutine($someAwfulObfruscatedCode));

?>

To decode, try replacing eval with echo, and voila, your code in-tact.

Examples of misguided attempts at securing code with eval include base64[en|de]code and url[en|de]code, but regardless of your encoding/decoding skills and functions, replacing eval with echo will get the code back in all functions of this sort.
aleosha at yandex dot ru
10-Mar-2006 09:43
There's a minor mistake in example that shows how to correctly use EVAL with IF statements.

Instead of
$str="\$refer=&\$total".$i.";";
eval($str);
Wich just puts value "total2" in your $refer variable, you should  use
$str="\$refer=&\$$total".$i.";";
This one will create the real referrer to the value of $total2 (5, in our case).
jnavratil at houston dot rr dot com
25-Feb-2006 07:39
"A return statement will terminate the evaluation of the string immediately. As of PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned." isn't strictly true as the eval can return a value through the side-effect of setting a variable.

<?php
function getValue()
{
   return
123;
}

function
testEval1()
{
   eval(
'return getValue();');
}

function
testEval2()
{
   eval(
'$rslt = getValue();');
   return
$rslt;
}

function
testEval3()
{
   return eval(
'return getValue();');
}

function
testEval4()
{
   return eval(
'getValue();');
}

print
'1:'.testEval1()."\n";
print
'2:'.testEval2()."\n";
print
'3:'.testEval3()."\n";
print
'4:'.testEval4()."\n";
?>

results in...

1:
2:123
3:123
4:

In case 1, the eval returns the result to an uncaring caller (contra: case 3).  In case 2, the eval makes the result available through the side-effect of setting '$rslt'.  In case 4, 'eval' returns null to an apparently caring caller (contra: case 1).
apmuthu at usa dot net
24-Feb-2006 01:02
Ref: Nick - SafireX, TfM, Nick Johnson - Pixelrific
Generic eval function

Replace the line:-
$string = preg_replace("/<\?=\s+(.*?)\s+\?>/", "<? echo $1; ?>", $string);
with
$string = preg_replace("/<\?=\s*(.*?)\s*\?>/", "<? echo $1; ?>", $string);

The "\s*" in the two places will enable 0 or more white spaces to exist after the "=" instead of the existing "\s+" which enables only 1 or more white spaces.

Also instead of using the eval function in the return statement of the function, it would be better to return only the string ready to perform eval and then do the eval in the main program where the scope and visibility of variables are known.
nick at hmsonline dot co dot uk
17-Feb-2006 12:22
Just a quick note on the functions below that use 'eval_mixed_helper' using add/remove slash do not work if the content includes PHP like code. Using base64 encode/decode solves this.

E.g.

function eval_mixed_helper($arr)
{
   return ('echo base64_decode("'.base64_encode($arr[1]).'");');
}
karig at karig dot net
01-Feb-2006 01:10
OK, here's what I've found to work for me:

Let's say I have a string like this, pulled from a much larger file:

$text = "<p>The following is generated by PHP:</p>\n"
   . '<?php $a = 6; $b = 4; $c = $a + $b; '
   . '
echo "<p>Variable c = $c</p>\n"; ?>'
   . "<p>This is just more text.</p>\n";

Doing this just echoes the PHP code (so a visitor can actually read it by viewing the web page's source) instead of executing it:

echo $text;

I wanted to have the PHP code in the text executed, so that the /result/ is echoed, and the code itself is not. Happily, all I needed to do to get this to work for me was this:

ob_start();
eval ('?>' . $text);
$text = ob_get_clean();
// Do whatever else you want with $text before outputting it
echo $text;

That little '?>' prepended to $text (suggested by a previous note here) seems to be the key. Note that I DON'T append a corresponding '<?php' to $text, as a previous note suggested; I tried that, and I got an error. But I've found that "eval ('?>' . $text);" works:

----
OUTPUT ----

The following is generated by PHP:

Variable c = 10

This is just more text
.

----
HTML REVEALED IN WEB-PAGE SOURCE ----

<
p>The following is generated by PHP:</p>
<
p>Variable c = 10</p>
<
p>This is just more text.</p>
jkuckartz1984 at hotmail dot com
29-Jan-2006 08:01
Might you have to do eval in if statements, you will find it's quite some task to make it work.

The only way to make it work is to make a reference to the eval'd variable. This example will show the different usage of eval in if-statements. It simply becomes clear that an eval() in an if() is not working as you want to.

<?php
$total2
=5;
$total3=0;
$i=2;
if (eval(
"\$total".$i.";")) {
   echo
"eval: total2 is full<br>";
} else {
   echo
"eval: total2 is empty<br>";
}
// returns "empty"
// eval without the ";" will generate a warning

$str="\$refer=&\$total".$i.";";
eval(
$str);
if (
$refer) {
   echo
"eval: total2 is full<br>";
} else {
   echo
"eval: total2 is empty<br>";
}
// returns "full"
?>
Sarangan Thuraisingham
21-Jan-2006 09:47
The eval function can be misused for Cross Site Scripting(XSS) as well. Les say we have this very trivial page that allows a user to enter a text and see it formated using different styles. If the site designer was lazy and used eval function to come up with somethig like this:
<?php
$mytxt
= $_GET["text"];
$strFormats = array( '<h1>$mytxt</h1>',
                    
'<h2>$mytxt</h2>',
                    
'<span class="style1">$mytxt</span>'); //so on

foreach ($strFormats as $style){
   eval(
"echo $style;");
}
?>
This page could be a target for XSS, because user input is not validated. So the hacker could enter any valid PHP commands and the site will execute it. Imagine what could happen if the injected script reads files like config.php and passed it to the hacker's site.

If the file permissions are not set correctly, the injected script could modify the current script. A form's action parameter can be set to a hacker's site or worse every transaction could be secretly posted to another website from within the server. Injected script could be something like this:
<?php
$filename
=basename($_SERVER['PHP_SELF']);
$fp = fopen($filename, "a");
$str = echo "<!-- XSS Vulnerability-->"; // could be any PHP command
fwrite($fp, $str);
fclose($fp);
?>

The golden rule is don't trust the user. Always validate data from the client side.
jurgen at person dot be
19-Dec-2005 01:27
eval() is used to protect (read: hide) source code. A well known way to encrypt some php code is security through obscurity.  Someone used eval(base64_encode(".....")); - which basically had 10-16 nested calls to eval(base64_encode()) inside the data.

E.g.
<?
eval(gzinflate(base64_decode('AjHRawIHG1ypUpudV.....')));
?>

However this can be decoded in this way:
<?
  
echo "\nDECODE nested eval(gzinflate()) by DEBO Jurgen <jurgen@person.be>\n\n";
  
   echo
"1. Reading coded.txt\n";
  
$fp1      = fopen ("coded.txt", "r");
  
$contents = fread ($fp1, filesize ("coded.txt"));
  
fclose($fp1);
  
   echo
"2. Decoding\n";
   while (
preg_match("/eval\(gzinflate/",$contents)) {
      
$contents=preg_replace("/<\?|\?>/", "", $contents);
       eval(
preg_replace("/eval/", "\$contents=", $contents));
   }
      
   echo
"3. Writing decoded.txt\n";
  
$fp2 = fopen("decoded.txt","w");
  
fwrite($fp2, trim($contents));
  
fclose($fp2);
?>
onlyphp
24-Nov-2005 10:59
To simulate the register_globals setting in php.ini, you must put it in the top of your php page:

function rg() {
  $ar = array($_POST, $_GET, $_SESSION, $_SERVER);
  foreach($ar as $ar_) {
   foreach($ar_as $key => $value) {
     eval("\$" . $key . " = \"" . $value . "\";");
   }
  }
}
matt at mattsoft dot net
11-Sep-2005 01:23
to load a php file to a variable then execute it, try this

<?php
$code
=file_get_contents("file.php");
$code=str_replace('<'.'?php','<'.'?',$code);
$code='?'.'>'.trim($code).'<'.'?';
eval(
$code);
?>

using < ?php within eval does not work, but < ? does. in case there is html in the file loaded, the script doesn't remove the < ?php and ? >, but insted adds ? > and < ? around the code loaded from the file. it's simple and works very well. I also broke up the tags in the 3rd and 4th lines of code to keep from having problems if the lines are commented out.
sadi at unicornsoftbd dot com
03-Sep-2005 09:49
I m going to give you my recent exploration about eval. I think you dont need all those complex functions using regex to work HTML in your code. when ever you call eval(), php thinks that it is within <? ?> tags. so all the problem rises. to solve the problem just close your php tag at first of the HTML string, then write the HTML string and then start the php tag.
this is some thing like:
<?php
$teststr
="?><html><body>this is the test</body></html><?php";
eval(
$teststr);
?>

i think this will work for you. at least this worked for me. if you find any problem with this please reply
Nick Johnson - Pixelrific
01-Sep-2005 12:43
In reference to Nick's functions below (which didnt work for me as is) and TfM's comment, this is fixed with a simple change to the pattern used by preg_replace_callback.  The pattern should be changed from

/\?>((.|\n)*?)<\?/

to

/\?>((.|\n)*?)<\?(php)?/

Making that small change will remove a "php" that is leftover in the string to be evaled, which eval trips on and complains about.
TfM
26-Aug-2005 08:06
Nick, I needed to replace "<?php" with "<?" before feeding the string to preg_replace_callback to make it work with recursive includes. Nice code anyway :)
Nick - SafireX
24-Aug-2005 07:26
This function will take any combination of HTML and (properly opened and closed)PHP that is given in a string, and return a value that is the HTML and the RESULT of that PHP code and return them both combined in the order that they were originally written.

This is a correction of an earlier script.
In the earlier varsion the preg_replace_callback search pattern was incorrect and wouldn't allow line breaks within the HTML sections.

I have also included a line to change shorthand <?= $var ?> to <? echo $var; ?>

This code is basicaly a version of the 'include' function which can be run on variables instead of files. Optionaly output can be captured using output buffering.

<?

function eval_mixed_helper($arr){
  return (
"echo stripslashes(\"".addslashes($arr[1])."\");");
  }

function
eval_mixed($string){
 
$string = "<? ?>".$string."<? ?>";
 
$string = preg_replace("/<\?=\s+(.*?)\s+\?>/", "<? echo $1; ?>", $string);
 
$string = str_replace('?>', '', str_replace( array('<?php', '<?'), '', preg_replace_callback( "/\?>((.|\n)*?)<\?/","eval_mixed_helper",$string) ) );
  return eval(
$string);
  }

// output to browser
eval_mixed($string);

// output to variable
ob_start();
eval_mixed($string);
$final_html = ob_get_clean();

?>
zcox522 at gmail dot com
18-Aug-2005 03:03
If you send headers after you call the eval() function, you may get this error:

PHP Error: (2) Cannot modify header information - headers already sent by (output started at something...)

In this case, surround your call to eval() with calls to some ob functions:

<?php
$eval
= "some code you want to execute";

ob_start();
eval(
$eval);
ob_end_clean();
?>
admiral [at] nuclearpixel [dot] com
16-Aug-2005 04:02
This function will take any combination of HTML and (properly opened and closed)PHP that is given in a string, and return a value that is the HTML and the RESULT of that PHP code and return them both combined in the order that they were originally written.

I tried using both the eval_html(gave me carp about using 's and "s in the HTML) and html_eval2(gave me the results of the PHP first, then all of the HTML afterwards) posted by the other users on this function's notes, but for some reason, neither of them would really work the way I had understood that they would work,(or in the case of some of my code, work at all)

So I combined the best of what I saw in both, and created eval_html3

<?php

function my_eval($arr) {
   return (
'echo stripslashes("'.addslashes($arr[0]).'");');
}

function
eval_html3($string) {
  
$string = '<?php ?>'.$string.'<?php ?>';
  
$string = str_replace( '?>', '', str_replace( array( '<?php', '<?' ), '', preg_replace_callback( "/\?>(.*?)(<\?php|<\?)/", "my_eval", $string ) ) );
   return eval(
$string);
}

?>

Good luck!
jphansen at uga dot edu
09-Aug-2005 03:43
I used eval() to restore a user's session data. I stored $_SESSION to a field in a database as

<?
addslashes
(var_export($_SESSION, TRUE))
?>

To restore it, I executed this code:

<?
eval("\$_SESSION = $session;");
// $session being the first line of code above
?>

Voila! Session restored.

Without eval(), $_SESSION = $session would have resulted in $_SESSION being a string instead of an array.
alexandrebr at ignorethis dot gmail dot com
08-Aug-2005 09:32
Like said before, use of 'eval' is not recommended, by the security issues.

A good use of eval, is to test your codes without having to create/save files on the hard drive.

You may want to create the script below, and send to your server, to help you to manage your database, for example...

<?
if(isset($_POST["code"])){
 
$code = get_magic_quotes_gpc()?
  
stripslashes($_POST["code"]):
  
$_POST["code"];

  eval(
"?>".$code);
}
else{
  echo
"<form method='post' action='eval.php'>";
  echo
"<textarea name='code'></textarea><br>";
  echo
"<input type='submit' value='Test the code above'>";
  echo
"</form>";
}
?>

With this, you can easily exec PHP codes on your site, without having to connect to the FTP and uploading files.....

Even tests with extensions like PHP_GD are allowed.

WARNING: If you wish to use the example above, PUT A PASSWORD PROTECTION! The function EVAL gives fully access to your site, so be careful.
the dank
30-Jul-2005 07:26
$foo1 = "the good,<br>";
$foo2 = "the bad,<br>";
$foo3 = "the ugly.";

for ($i=1; $i <=3; $i++)
{
     eval("\$_SESSION['myVar$i'] = \$foo".$i.";");
}

//use below to show what's in session:

echo "<h3>SESSION</h3>";
echo "<table border=1 width=50%>";
echo "<tr bgcolor=\"#3399FF\">";
echo "<td><b><font color=\"#FFFFFF\">Variable Name</font></b></td>";
echo "<td><b><font color=\"#FFFFFF\">Value</font></b></td></tr>";
while(list($key, $val) = each($_SESSION))
{
   echo "<tr><td>$key</td><td><b>$val</b></td></tr>";
}
echo "</table>";
die();

/*---------------------------------------------------------
Prints:
myVar1    the good,
myVar2    the bad,
myVar3    the ugly.
*/
privat at timo-damm dot de
29-Jul-2005 04:03
Using the html_eval() some notes above I experienced problems related to *dirty* html. This function is less critical:

function html_eval2($string) {
  return preg_replace_callback("/<\?php(.*?)\?>/","my_eval",$string);
}

function my_eval($arr) {
  return eval($arr[1]);
}

Timo
license_to_il
26-Jul-2005 03:44
// the array in my code
$my_ar    =    array(2,3,4,5);

// eval in code or pulled from db
eval("print_r(\$my_ar);");

output:
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 )
macronesia at macronesia dot com
03-Jul-2005 08:35
Instead of using eval for template logic, use str_replace to replace variables with proper code, such as XHTML.
andrejkw
24-Jun-2005 08:50
To use eval output as a variable without the user seeing the output, use this:

<?php

ob_start
();
eval(
"whatever you want");
$eval_buffer = ob_get_contents();
ob_end_clean();

echo
$eval_buffer;

?>

Everything that eval produces will now be stored inside $eval_buffer.
Jesse
19-Jun-2005 04:25
a cool way to use eval is to convert strings into variable names.
this is a subsitute for using arrays.
look at this code:
<?php
for($a=1; $a<=5; $a++){
   eval(
"$"."variable".$a."=".$a.";");
}
?>
this will create variables called variable1, variable2, and so on, that are equal to 1, 2, and so on.
i recently used this to help a friend make a Flash game that sent variables like that to PHP.
1413 at blargh dot com
10-Jun-2005 03:58
Just a note when using eval and expecting return values - the eval()'ed string must do the returning.  Take the following example script:

<?php

function ReturnArray()
{
  return array(
"foo"=>1, "bar"=>2);
}

$test = eval("ReturnArray();");
print(
"Got back $test (".count($test).")\n");

$test = eval("return ReturnArray();");
print(
"Got back $test (".count($test).")\n");

?>

You will get back:

Got back  (0)
Got back Array (2)

This ran me afoul for a little bit, but is the way eval() is supposed to work (eval is evaluating a new PHP script).
jtraenkner
11-Apr-2005 12:11
Using eval inside loops is very slow, so try avoiding code like
<?php
for($i=0;$i<10;$i++) {
   eval(
'do_something()');
}
?>

If you absolutely have to, include the entire loop in eval:
<?php
eval('for($i=0;$i<10;$i++) {'.
  
'do_something();'.
  
'}');
?>
tom
29-Mar-2005 03:59
Eval can't be used as a callback function so if you want to use the eval function name dynamically use this simple work around:

<?

if ($function_name == "eval")
{
 eval(
$stuff);
}
else
{
 
$function_name($stuff);
}

?>
Ben Grabkowitz
27-Mar-2005 10:57
The eval function becomes incredibly useful when dealing with static class members and variables.

For instance:

Lets say you have 3 classes; Foo, BarA and BarB, where BarA and BarB are children of Foo.

Now lets also say that both BarA and BarB contain a static member function called getDataSource().

To call getDataSource() you would have to use the syntax:

BarA::getDataSource();
BarB::getDataSource();

But lets say you need to access getDataSource() from inside class Foo during an instance of either BarA or BarB.

You can use eval to do something like this:
eval('$dataSource=' . get_class($this) . '::getDataSource();');
francois at bonzon dot com
28-Feb-2005 11:20
An obvious security reminder, which I think wasn't yet mentioned here. Special care is required when variables entered by the user are passed to the eval() function. You should validate those user inputs, and really make sure they have the format you expect.

E.g., if you evaluate math expressions with something like

<?php
 
eval("\$result = $equation;");
?>

without any check on the $equation variable, a bad user could enter in the $equation field

""; echo file_get_contents('/etc/passwd')

- or whatever PHP code he wants! - which would evaluate to

<?php
  $result
= ""; echo file_get_contents('/etc/passwd');
?>

and seriously compromising your security!
avenger at buynet dot com dot br
09-Feb-2005 12:52
This is a small code that uses 'eval' with a foreach (maybe 'for' loop), to fill variables. This is very useful in some hard situations:

<html><title>for loop</title><body><p align=center>
 <?php
  $thing
= array("a","b","c");
 
$a = "bah" ; $b = "bleh2"; $c = "bluh3";
  print(
"Vars b4: $a, $b, $c. ");
  foreach (
$thing as $thingy ) {
   print(
"$thingy, ");
   eval(
"\$$thingy = \"$thingy\";");
  };
  print(
"vars aft: $a, $b, $c.");
 
?>
</p></body></html>
critmas at hotmail dot com
09-Feb-2005 04:46
I am using the eval(String) function as an alternate to processing instructions for XML code.
i.e.
<tag>something that I $need</tag>
when I read the value of the node (using DOM)
I ask php to evaluate the line for me to replace the value of $need.

Might be a hack, comments welcome
mat.wilmots (at) wanadoo (dot) fr
21-Jan-2005 10:16
Just a little note : eval is not a function.
Something like this

<?php
register_tick_function
('eval', array('break;'));
declare(
ticks=1)
{
   while(
true)
   {
         echo
"Not broken yet\n";
   }
}

?>

doesn't work, it says
Unable to call eval() - function does not exist
jasperbg at gmail dot com
04-Jan-2005 02:09
There's a much easier way to dynamically load PHP pages:

eval('?>' . $the_page . '<?php ');

where $the_page is a standard PHP page with <?php ... ?> tags around the portions to be parsed.
arnico at c4 dot lv
21-Dec-2004 07:28
Dynamically loading php pages!
In michael example ( 02-Sep-2004 05:16) is one big problem. Try to load php page with this content :
-----------------------
<?php

$a
= 1;

if(
$a == 1){

?>
<br />ir?<br />
<?php

}

?>
------------------------

Ups? :) maybe easier way is to do something like that ? please comments :
<?php

function eval_html($string) {

  
$string = preg_replace("/\?>(.*?)(<\?php|<\?)/si", "echo \"\\1\";",$string);
  
$string = str_replace("<?php", "", $string);
  
$string = str_replace("?>", "", $string);
   return eval(
$string);
}

$filename = "page.php";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

echo
eval_html($contents);

?>

The html source will be replaced with echo. and problem is gone :) or there are other problems ? please comments.

P.S. sorry about my bad English
Amedeo
09-Dec-2004 04:00
It's more easy to write the code to be evaluated if you put it between single quotes:

<?php
   $var
= "aaa";
  
$i = 4;
  
$code = '$ARGS[$i]["GID"] = $var;';
   eval(
$code);
   echo (
"<pre>");
  
print_r($ARGS);
   echo (
"</pre>");
?>

Which will output

Array
(
   [4] => Array
       (
           [GID] => aaa
       )
)
mahaixing at hotmail dot com
09-Oct-2004 11:49
When using Dynamic Proxy design pattern we must create a class automaticly. Here is a sample code.

$clazz = "class SomeClass { var \$value = 'somevalue'; function show() { echo get_class(\$this);}}";

eval($clazz);

$instance = new SomeClass;

// Here output 'somevalue';
echo $instance->value;

echo "<br>";

//Here output 'someclass'
$instance->show();
evildictaitor at hotmail dot com
16-Aug-2004 04:00
Be careful when using eval() on heavy usage sites in PHP 4.0+ as it takes vastly longer to activate due to the limitations of the Zend engine.

The Zend engine changes the PHP to a binary structure at the START of the file, and then parses it. Every time an eval is called, however, it has to reactivate the parsing procedure and convert the eval()'d code into usable binary format again.

Basically, if you eval() code, it takes as long as calling a new php page with the same code inside.
13-Jul-2004 12: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
info [at] derosetechnologies [dot] com
13-Jun-2004 08:15
"Bart Koelman"  's  example above (OutputPhpDocument), though thouroughly functional , would benefit by using the "extract()" function in lieu of his variable exporting  solution. I.e.:
<?
  reset
($GLOBALS);
  while (list (
$key, $val) = each ($GLOBALS))
  {
   eval(
"\$" . "\$key = \"$val\";");
  }
?>

Can be replaced with a single line:
<?extract($GLOBALS, EXTR_SKIP | EXTR_REFS);?>

Addtionally, this latter alternative will load the global variables as references instead of 'copies'. (Meaning that if a value is altered inside the function ,  that modification will also be effected outside of the OutputPhpDocument() function.
Mark Aufflick (mark at pumptheory dot com)
18-Nov-2003 01:49
Based on the excellent example by olivier at revenu dot nom dot fr, I have extended it to allow the <?= ... ?> tagged style of embedded php code:

<?php

function eval_buffer($string) {
  
ob_start();
   eval(
"$string[2];");
  
$return = ob_get_contents();
  
ob_end_clean();
   return
$return;
}

function
eval_print_buffer($string) {
  
ob_start();
   eval(
"print $string[2];");
  
$return = ob_get_contents();
  
ob_end_clean();
   return
$return;
}

function
eval_html($string) {
  
$string = preg_replace_callback("/(<\?=)(.*?)\?>/si",
                                  
"eval_print_buffer",$string);
   return
preg_replace_callback("/(<\?php|<\?)(.*?)\?>/si",
                                
"eval_buffer",$string);
}

?>
David Schumann
05-Nov-2003 03:17
To evaluate math expressions (multiply, divide, addition, subtraction, percentages), use the following function, based on Taras Young's 'evalsum' function posted earlier:

function matheval($equation){
       $equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
       $equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
       // you could use str_replace on this next line
       // if you really, really want to fine-tune this equation
       $equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
       if ( $equation == "" ) {
               $return = 0;
       } else {
               eval("\$return=" . $equation . ";");
       }
       return $return;
}

You could easily extend this to include exponents, square roots, or really any other mathematical function. I use it in a 'price each' field on a purchase order form. The user can type in '$10.00-25%' and get 7.50 as the result.
G Systemacher
15-May-2003 12:10
An example of eval within a function within a class sitting on PEAR DB whose purpose is to push onto a result array named: result_ appended with a parameter key.

function set_result_array($fn_request_key = '[DEFAULT]', $fn_result) {
   $target_array_string = 'result_'.$fn_request_key;
//    eval ("global \$\$target_array_string;");
   eval("\$target_array =& this->\$target_array_string;");
   if (!is_array($target_array)) { $target_array = array(); }
   return array_push($target_array, $fn_result);
}

What does this illustrate? An example of using eval to create a reference to an object member by reference (=&).

The eval ("global ....)  line is commented out as I couldn't get this to work for some reason.
Smooth
28-Jan-2003 04:53
/* It seems that eval() won't return by reference: */

function &get_ref ($var) {
  ...
  return $reference;
}

/* The following code returns a parse error                  */
/* (expecting `T_NEW' or `T_STRING' or `T_VARIABLE' or `'$'') */

$r =& eval ('return get_ref ($v);');

/* But thinking "inside the box" you can always do this... */

eval ('$r =&  get_ref ($v);');

(I'm using PHP Version 4.2.3)
barry at sanyuan dot com dot au
09-Dec-2002 10:03
Almost driving me to the ends of insanity i found the scripts above for eval html with php inside would not work on strings like :

<?php for($i=1; $i < 7; $i++) { ?>

<?php echo $i; ?>

additional html here

<? } ?>

In the end, as another option for executing string with both html and php was with tmpnam... eg.

   $tmpfname = tempnam ("/tmp", "FOO");
   $fp = fopen($tmpfname, "w");
   fwrite($fp, $CONTENT[tpl_body]);
   fclose($fp);
   include($tmpfname);
   unlink($tmpfname);

It works perfectly for me and is an alternative to eval for php and html.
olivier at revenu dot nom dot fr
09-Jul-2002 12:44
Here an improved function of evalHTML discussed above (see brandon@louish.net or nathan vonnahme).

I do some bench with a multi-line string contain php code <?echo "hello" ?> :

for 1200 eval/replace => proceed 10 times faster
for 12 eval/replace => proceed 3 times faster

function also support both <? and <?php style... enjoy !

**
BEGIN **

function
eval_buffer($string) {
  
ob_start();
   eval(
"$string[2];");
  
$ret = ob_get_contents();
  
ob_end_clean();
   return
$ret;
}

function
eval_html($string) {
   return
preg_replace_callback("/(<\?php|<\?)(.*?)\?>/si",
"eval_buffer",$string);
}

**
END **
?>
for older php version (< 4.0.5), it also possible to do it with preg_replace but it's a little slower (20 %) :

** BEGIN **

function eval_buffer($string) {
   ob_start();
   eval(stripslashes("$string;"));
   $string = ob_get_contents();
   ob_end_clean();
   return $string;
}

function eval_html($string) {
   return preg_replace("/(<\?php|<\?)(.*?)\?>/sie",
"eval_buffer('\\2')",$string);
}

** END **