Php – how to execute php from a database

databasePHP

Warning: very outdated question with an awful idea. Storing code, whether it be PHP, javascript or even HTML is never a good idea. Leaving this here only for documentation purposes

I've got a bit of an awkward problem.

Normally when putting stuff in a database, this will be saved in the way it is.
So, if the saved stuff is:

<?php echo "hi!"; ?>

This will just be output as 'hi!' when called.
However, in my case I'm saving plain text into a database. I'm not doing any verifying to check for these codes and I've turned off magic quotes to prevent the stuff from being escaped.

When getting the data from the db and putting it inside a page (ofcourse before the page if fully loaded so the php should be executed) this shows up in the source-code as being a ?php tag and thus invisible (on safari at least) because it is a not-known tag for output.

the data-block consists of a kind of 'Joomla-ish' template-code. HTML-tags, Style(css), Javascript blocks and php could all be in there. Stuff like css, js, etc. works, but server-sided code doesn't.

Any ideas on how to get this to work or why it isn't working? The database is in mySQL and MyISAM as the storage engine. The field I'm saving it in is a longtext. I'm using php5 (which states on the w3c site using magic quotes is not good practice as it will be deleted in the php6 because it poses a lot of security risks apart from solving a few).

I've tried using eval(), but there's one little problem. the eval() function asumes this is php, but oftentimes it won't be. It will mostly be html with some php blocks in it.

Best Answer

I recommend against storing PHP in the database. The database is for data, not code.

If you need conditionally-run code, put it in .php files and use include() to execute it.

If you need dynamic content, you can put that in the database and then just echo it. No need to use eval().

Don't forget to escape output with htmlentities().