Before I show you how, you should know that storing PHP code in your database might not be the best idea. For one thing, evaluating the code will require more resources than normally executing code. Also, if you plan on allowing users submit code which will then be evaluated, you're setting yourself up for disaster.
PHP provides a function for evaluating code in a string: eval(). Basically you use it like this:
PHP Code:
$code; //the code you pulled from the database
eval($code);
There are a couple of catches, however. For one, any output resulting from the eval'd code will not be sent. One workaround for this problem is to append an output buffer into the eval'd code:
PHP Code:
$code;
$pre = 'ob_start(); ';
$post = ' $output = ob_get_clean();';
eval($pre . $code . $post);
echo $output;
Notice that variables created by eval persist for the remainder of the script. eval can also modify existing variables so you may want to be careful to avoid collisions (eval making use of or overwriting a pre-existing variable in a way that was not intended).
Also...
eval assumes you are already in PHP mode (in other words you should not begin your eval'd code with an opening tag <?php or end with a closing tag ?>).
Just to reiterate: using eval to run code stored in a database isn't a very common task, you may want to rethink your approach.
Last edited by NullPointer; 12-30-2009 at 10:21 PM..
|