开发者

Is it possible to execute PHP code returned from a MySQL query result?

The issue I am having is as follows: I have a MySQL table that contains details for page content I wish to display on my site. The content for one of my pages however I w开发者_运维技巧anted to contain some actual PHP code to be executed, not just printed as a string. For example:

require_once("Class.php");
Class::Function("Some Text For a Parameter");

I want this code to execute somehow when the sql query is returned but as it stands, it just prints that text out. Is there a way to achieve what I want?

Thankyou in advance for your time,

Regards,

Stephen.


You can do it with eval(), but you shouldn't.


they are several ways to achieve the storage of dynamic elements :

  • eval(str) : you can evaluate as php code any string coming from you database. This is not very wise if what is stored in the database comes directly from a user input field. You never know what is going to be inserted and it could potentially be harmful code (harmful to the security of your server)

  • save / include : you could save what comes from your database in a temporary file and include() that file in-place in your php code. This does not seem to be secure either if anyone can store anything in your database

  • use a templating engine that has a reasonnable command footprint like smarty or mustache. you can store the templates in your database and execute them. If you trust the implementation of the templating language (and disable native php calls inside smarty for example) the template will need to have a correct syntax before execution can begin

As a general rule of thumb, it is very hard to protect such dynamic php code inclusion, so it should be considered as bad practice.

You should consider a DSL (domain specific language) for which you will trust the parser/compiler and execution engine.

If security is not a concern (because your application will not be public for example) then it can be perfectly valid and effective to store php fragments in the database.

I hope this will help you

Jerome Wagner


I do a variation of this in my personal CMS by doing a bbcode of sorts. I enclose php to evaluate inside of [code][/code] tags, then when displaying I have a function that uses regular expressions to grab the contents of code inside the [code] tags to run. It in turn builds the code such that it closes the text echo, runs the script, then starts the text echo again. Perhaps the explanation is a bit simplistic, but you get the idea.

I would definitely avoid eval!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜