Store php code in sql and execute it?

gluxon

Member
Messages
31
Reaction score
1
Points
8
I'm starting up my own CMS, so one of the problems I've come across is that I can't store php coding in a MySQL table and execute it. It'll show up as HTML.

I realize I could write the whole thing to a file, then include it, but I'd like to see if there's another way other than that.

Thanks.
 

dlukin

New Member
Messages
427
Reaction score
25
Points
0
You can always try to eval( $code ) where $code is the php code you stored in the database.

But including a file has much less overhead than 1) making a database query and then 2) eval() the result.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
But including a file has much less overhead than 1) making a database query and then 2) eval() the result.
Not to mention that using eval will open up a potential injection vulnerability. It has its uses, but as Rasmus Lerdorf (PHP's inventor) once said,
If eval() is the answer, you're almost certainly asking the wrong question.

Of course, writing to a file & including it introduces the same vulnerability, and has even more overhead. OP, I have to ask: why do you need to evaluate arbitrary PHP code?
 
Last edited:

gluxon

Member
Messages
31
Reaction score
1
Points
8
why do you need to evaluate arbitrary PHP code?

So I can have php in pages :/

For example, I used to use $BASE in my links and images, so the links would still work when I move the page (I realize I don't need to do this anymore with mod_rewrite and php). That wouldn't work when the page is placed in the database then executed.
 

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
For what it's worth, storing PHP in a database for execution is a hideously bad way of getting around a problem. In no case should you ever have to do it.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
A safer option is to use a limited template engine, storing strings in the template language. If you only need variable replacement, you can use preg_replace_callback to replace variable names with values.

PHP:
function lookup_var($matches) {
  if (count($matches) <= 2) {
    // simple variable syntax
    ...
    // e.g. "return $_GLOBALS[$matches[0]];", but that's still potentially unsafe
  } else {
    // complex variable syntax
    ...
  }
}

preg_replace_callback('/\$(?:(\w+)|{([^}]+)})/', 'lookup_var', $str);
 
Top