Is it possible to load an execute PHP code out of the database?
If I had PHP code in the database, could I "include" that somehow in PHP and execute it? Well, sure I could write out a file with that content and just include that file, but maybe PHP has got something similar to eval() of J开发者_JS百科avaScript?
Yes, PHP has eval()
too, but it is regarded very bad practice to use it.
This question discusses the major points well, without condemning it totally.
Most often, if eval()
comes up, it is worth taking a hard look at the program you're building: There is probably a better way to do it. For example, if you want to fill data values into HTML code that is stored in a data base, a templating engine of some sort might be a better idea.
Note that not using eval()
but writing out a file from the db and including that will have exactly the same security risk though...the point is not so much to eval()
or not to eval()
the problem is: what if someone hacks into your database, and has the ability to modify the PHP code? the'd be capable of having your server run their php script, and do what ever they like.
There is eval() for PHP. But please, never-ever use it! :D
Yes!
http://php.net/manual/en/function.eval.php
You can evaluate some code using the eval
function -- but it's generally considered bad practice, and a bit dangerous, to use it.
(Well, actually, it's the same function name as in Javascript ;-) -- and it's bad practice in both languages -- what a coincidence ; or not)
Another solution that is sometimes used is to :
- have your PHP code in a database
- fetch it sometimes (not everytime) and store it to a file, used as a caching mecanism
include
that file -- which will be executed
I've seen some pretty old CMS work this way, for instance... But note they where mostly using files as cache (To not make too many requests to the DB) -- even if it worked quite well.
What about using file cache? You can always store PHP code temporarly in file and include it. Simple logic with file generation, storing in cache, including correct file and refreshing old files (md5 checksum + file cache made timestamp + modification timestamp). Then just compare both timestamps to know if cache update is needed.
精彩评论