Programming - - By Lachlan Donald

Eval is dead! Long live Eval!

I’m Lachlan Donald, the new guy here at SitePoint. I’ll be helping out with PHP blog content along with the other guys here.

Eval seems to be a hot topic of discussion lately, especially in light of the recent vBulletin exploits and past exploits in common applications such as phpMyAdmin. Eval is one of the functions in PHP which can execute arbitrary code. Generally eval is used either by inexperienced programmers for a variety of misguided reasons, or by people attempting to push the boundries of PHP. What inspired me to post this article was this quote from Rasmus Lerdorf, creator of PHP:

If eval() is the answer, you’re almost certainly asking the wrong question.

Perhaps it’s just my argumentative nature, but when people use that quote I always wonder whether there are any common problems that are only solvable by using eval. Before I get into the nitty-gritty details, a brief recap of what eval actually does from the PHP manual:

mixed eval ( string code_str )

eval() evaluates the string given in code_str as PHP code.
Among other things, this can be useful for storing code in a database
text field for later execution.

To an inexperienced programmer this might sound like a fantastic idea, allowing for snippets of code to be stored in a database and executed depending on other criteria stored along with the record. In practice, writing an application that interprets pieces of code that are stored along with user data is asking for trouble. Take this example, which calls a function and assigns the result to a variable.

function getTemplate($tpl) { return "a template"; }

eval('$content = getTemplate("'.$_GET['tpl'].'");');

With Magic Quotes disabled this creates a huge security hole, as all an attacker must do to execute arbitrary php code is insert it into the request url. For instance, the following query string causes the contents of the current directory to be output to the screen.


Naturally this example is contrived, but its very similar to the code that was the target of recent attacks on PHPBB and VBulletin. This sort of code is generally a result of lazy programming or bad design. Some more advanced uses of Eval are less dangerous and more interesting, for instance:

Please feel free to post feedback or examples of good or bad use of eval.