Implicit Evaluation with PHP

12 December 2005

My Day Job Precludes Me From Keeping It Real

XQuery for PHP will have to sit for idle for a few days, as I won’t develop it at work (licensing; ownership; job priorities; etc) so instead, I’d like to discuss a pitfall of implicit evaluation.

One thing implicit evaluation allows you to do, which I avoid, is drastically reducing the amount of code you write. Consider the following:

$action = "update";
if ($action == "insert") {
$sql = "INSERT INTO President (Name, SworeInDate) VALUES('$strName', '" . date("Y-m-d", $datSworeIn) . "')";
} else {
$sql = "UPDATE President SET SworeInDate=Now() WHERE Id=$id";
}
$action($sql);

This is fairly self-explanatory, but is still too magical for my tastes. There are two problems with magical code:

  1. The learning curve for anyone but the original developer is too high.
  2. Eventually, the code will break.

Original development of magical code is easy enough, as you must start from the beginning, and build on already working code. However, at the point code breaks, it can be anywhere in the process.

In addition to the learning curve and maintenance issues, magical code does not enforce (and approaches encouraging!) insecure code. Just imagine $_POST[”action”]();. With trusted input, it’s fine, but with <form action=”?”><input name=”action” value=”unlink($_SERVER[”PHP_SELF”]);php_info” type=”hidden”></form> things can get interesting.

Worse yet, if register_globals is turned on (hurry up, PHP 6. Register_globals is no longer an option in PHP6) you might call $action(). Then, even if you do have some amount of validation for assigning an action, a user supplied function name COULD slip through depending on the stability of your code.

So please: Use implicit evaluation responsibly. Use it in place of eval();. But don’t use it to shortcut things that should be explicitly checked, or things that save a minute now and will cost future developers hours and hours.

No Comments currently posted.

Post a comment on this entry: