Thursday, July 15, 2010

PHP - The magic of php eval() function

It's been a while since I last post to my blog and today I would like to share with you my experience with the so called eval() function in PHP.

The function eval() basically:
"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 incode_str. To mix HTML output and PHP code you can use a closing PHP tag to leave PHP mode.
Also remember that variables given values under eval() will retain these values in the main script afterwards."

for example:
<?php eval("echo 'test';"); ?>
will have the same output as
<?php echo "test"; ?>

so by this method, we can do any dynamic programming in php as long as the syntax is correct.

I came out with an experiment where I host a class script somewhere and with just 2 lines of code I can use the class in another web server without any problem.

In the external server I set a script to output the class codes:
In php, to include the class I just have to use these 2 lines:
$class_common = file_get_contents("");
eval("?>".htmlspecialchars_decode($class_common)."<?php ");

So now I can use:
$common = new class_common();

And the function will run as it is as it were on the same server.

The issue on this of course the load time of the script is vary depending on how fast the server can get the script from the other server but it is worthy in some cases.

No comments: