...

View Full Version : Keeping PHP code in MySQL DB



guvenck
04-02-2007, 10:31 PM
Hello,

I would like to enter PHP code in a textarea and keep it in a DB field. When the time comes I would like to be able to call the code from the DB and use it (execute or include it). Is this possible?

johnnyb
04-02-2007, 10:40 PM
Hi,

Yes, this should be possible.

When you store the data in the DB you'll need to escape it so that any queries or special characters in your code won't be executed by the DB server. If you're using MySQL try this function that I found on either php.net or mysql.com, (I can't remember which):

function quote_safe($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not a number or a numeric string
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
It adds quotation marks to text automatically so you don't have to, and renders your data safe for a mysql query. If you're not using MySQL addslashes() may suffice, but check your DB's documentation to be safe.


When you bring the data out of the database you shouldn't need to stripslashes or anything. Just load the code into a string variable, and run eval() on it.

Example:

eval($code_to_be_executed);


That's it!

aedrin
04-02-2007, 10:42 PM
Just remember that you are adding a large security risk whenever you use eval().

I would consider alternatives to storing PHP in a database (there shouldn't be a need for it).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum