jumping on the “escape input, filter output” bandwagon
Sunday, August 28th, 2005It’s true, I’m jumping on board the “escape input, filter output” bandwagon. This mantra, coined by Chris Shiflett of Brainbulb, and made oh-so-popular by my pal Ben Ramsey.
Here’s how I do it in my most recent PHP project, using PHP’s PEAR DB library (because it was MySQL, and now it’s postgreSQL):
For escaping:
$stmt = $dbh->prepare(”INSERT INTO table (thing) VALUES (?)”);
$sql_data = array($data_from_user_clean);
$dbh->execute($stmt, $sql_data);
PEAR DB’s escapeSimple will perform the equivalent of mysql_real_escape_string() or whatever db implementation you’ve got. Also, the prepare statement is pretty robust, ensuring that whatever gets plopped in is a value, and not just inserted into the statement using PHP’s “.” concatentation.
For filtering:
// .. check $dbh for error
Which whips out, among a few other things (on arrays and single pieces of data):
I’m also using Smarty Template Engine for every piece of displayed code, which serves as a great variable modifier and “filterer” of bad-ness. Also, I’ve got my templates locked away from the html doc root, and apache/nobody/httpd does not own them.
Locked down? Somewhat. She’s getting there.
