PHP

Easily Get PHP Code From Database & Execute / Parse It

Do you have some custom PHP code in database that you wish to retrieve and parse / execute and show the output in the browser? Here’s an easy way to do just that.

How to Easily Get PHP Code From Database & Execute / Parse It

One way to parse PHP code is to use “eval” . So before we look at how to parse the PHP content from database, let’s look at the general way to parse PHP code using eval. Consider the following example:

Example 1: Parse / Execute PHP code in general

<?php 
$fruit1 = 'Apples';
$fruit2 = 'Grapes';
$my_text = 'I like $fruit1 and $fruit2';
echo $my_text . "<br>"; 
eval("$my_text = \"$my_text\";"); 
echo $my_text . "<br>"; 
?>

When you execute the above code, you will see the following output:

I like $fruit1 and $fruit2
I like Apples and Grapes

So simply remove the first echo if you want to use it to parse general PHP code. Now let’s see how to use eval on PHP content from database.

Example 2: Get PHP code from database and Parse / Execute it

Let’s say that you have some custom PHP code in database that you wish to run and show the output of. So consider the following code as stored in database:

<form method="post" class="my_form_class" id="my_form" action="<?php echo $_SERVER['PHP_SELF']; ?>" >

</form>

Note the action attribute of the form. If you get this code from database and try to run it, you will see an error that breaks the code because the code from database contains the PHP start and closing tags. So to avoid that, you will need to modify our code a bit to make it work without breaking. So here’s how it can be done:

$final_content = eval('?>' . $database_content_with_php_code . '<?php ');

echo $final_content;

Follow the above steps and you will see that the content can now be shown properly in browser.

NOTE:

Using “eval” is considered dangerous to use and not it is not recommended because of the vulnerabilities associated with it. Read more about eval here.

Your Turn!

Do you know of any other ways to get PHP code from database and parse / execute it? Please feel free to share your thoughts by commenting below.

Share your thoughts, comment below now!

*

*