How to Execute PHP That Is Stored in a MySQL Database

How do I execute PHP that is stored in a MySQL database?

You can use the eval command for this. I would recommend against this though, because there's a lot of pitfalls using this approach. Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh).

See When is eval evil in php? for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution.

Addition: Another good article with some references to exploits is this blogpost. Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.

Execute PHP code stored in a database

You could use PHP's eval to run code stored on a database.

$code = get_code_from_db();
eval($code); // will evaluate (run) code stored in $code variable

Careful though. eval is a function that needs to be treated carefully. It could be the source of bugs, security holes, you name it, if you don't think about the implications of the stored code.

Run PHP code stored in a database

Sounds like you're talking about eval() - but I'd be wary of using it. If you do, be extremely careful.

"If eval() is the answer, you're almost certainly asking the wrong question." -Rasmus Lerdorf

You'd probably need to strip the <?php and ?> tags, and watch for double quotes surrounding variables you don't want to replace:

$s=0;
eval('$s = "my name is";');
echo $s;

How to execute a PHP function which is stored in MySQL database

You could use eval() like this:

$result = mysqli_query($connection, "SELECT * FROM `modules` WHERE uid=2 LIMIT 0, 30");
$row = mysqli_fetch_assoc($result);
$function = $row['source'];

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

I strongly disadvise you to store your functions in a database though, since it brings in a huge security risk. Instead, you could do it like this:

uid | moduleName  | source             | responsiveCode | active 
----------------------------------------------------------------
2 | Testimonial | this is a function | 12 | 0

$result = mysqli_query($connection, "SELECT * FROM `modules` WHERE uid=2 LIMIT 0, 30");
$row = mysqli_fetch_assoc($result);
echo $row['source'] . getUrl(); //will still print the same

Is there any way I can execute a PHP script from MySQL?

It's possible, See the MySQL FAQ for an explanation of how

Can triggers call an external application through a UDF?

But it's likely to be bad design on your part if you have to resort to this

Run PHP code from Database Query result

You can execute it in two ways:

  1. use the eval('here comes the text you get from db') function.
  2. you can write the text to a file and then call the file.

Store PHP code on MySQL and get it to run


$str = '<?php echo "string"; ?>'; // Your DB content

eval("?> $str <?php ");


Related Topics



Leave a reply



Submit