I'm working on a php project, and I want to run code that's fetched from a MySQL database. There's no chance of unsafe code being injected, so the only thing I'm worried about is performace. Should I use eval() so I can directly run the code, or parse it so that call_user_func() runs it instead?
For example, if the code I fetched was "myfunc(1,2,3); anotherFunc(3,2,1);"
I can eval() it directly to run the code.
But for call_user_func(), I'd have to parse the string so that it can be ran. So which is the better function to use in this case?
Storing PHP in the database is a bad design smell in itself; even though in this case you are pretty sure it can never contain unsafe code, it is always good to minimize the number of assumptions or defenses like that you have to make. If you store PHP code in the database, then an attack in which an attacker gains access to your database quickly becomes a lot more serious, turning into an attack in which an attacker can run arbitrary code! I know that having your database compromised like this is highly unlikely, but nonetheless it is good security practice not to let even an unlikely situation compromise your system more than it needs to.
Many people agree that eval() should always, without exception, be avoided in PHP code. There's always an alternative.
In this case, however, I think that I would have to say that using eval() would be the best solution for you, because you are already storing PHP code in the DB, so using eval() is not going to increase your risk any further than that.
I would, however, recommend that
I'm sorry if this answer seems a bit reactionary; I just happen to feel this sort of thing is very important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With