I would strongly recommend against doing what you're asking to do. There are a number of very good reasons for this.
The answer to the question, as others have said, is to use eval()
. However, eval()
has several major issues with it.
Firstly, to follow-up from the comments on the question, code run through it is executed significantly slower than regular PHP code. Although PHP is a scripted language, it does have optimisations to make run faster. None of these optimisations work for an eval block, because the scripting engine can't know what the code will look like until it actually runs it.
Not only that, but loading the code from the database will also be slower than loading it from a file using a regular include()
statement.
Secondly, eval()
is one of the biggest security headaches you can have. An eval()
statement will run any PHP code it is given, which means that an attacker can manipulate the code will be able to do anything on your server. In short, a single eval()
statement in your code can turn a minor hack into a catastrophic one.
One alternative solution that doesn't involve changing your concept too much would be to save the PHP code to a file rather than the DB. This would allow you to simple include()
it at the appropriate time, and would eliminate the speed issues discussed above. You could still use the DB to store it if you wished, and have it export to a cache file using a cron job or similar, or you could just save it directly to the file.
However, this solution wouldn't necessarily eliminate the security risks. You would still be running effectively arbitrary code, which would still mean that a hacker could do a lot of damage with a relatively simple hack.
I would therefore recommend re-thinking why you need to allow user-input PHP code to be entered into your software.
eval
you won't get any speed-up from opcode caches either :) – Ja͢ck May 14 '12 at 4:45