Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use eval() or call_user_func()?

Tags:

php

eval

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?

like image 957
Drahcir Avatar asked Mar 19 '09 15:03

Drahcir


1 Answers

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

  1. You try to validate the code before you eval() it, by being conservative in what you allow. Assume that somehow an attacker got into your database even thought that is unlikely.
  2. You at least give some serious thought to rewriting your application so that PHP code is not stored in a database. If you are storing complex data structures, think about something like JSON or even XML instead. Safe parsers exist for these.

I'm sorry if this answer seems a bit reactionary; I just happen to feel this sort of thing is very important.

like image 66
thomasrutter Avatar answered Oct 22 '22 07:10

thomasrutter