I’m doing a PHP OO project and long been thinking about, where to put variable sanitization. Make the object methods all around, ready to rumble and do the sanitization or give the coder some freedom and space for negligence to sanitize all the data by himself and make the functions dumb executors?
Which one is the preferred OO conform way?
class something
{
public function getCategoryByCID($cid)
{
if (!is_array($cid))
$cid = (array)$cid;
$cid = implode("','", $cid);
$cid = sanitizemeHARD($cid);
$sql = "SELECT * FROM cat WHERE (cat_cid IN ('$cid'))";
return $db->q($sql);
}
}
$c = new something();
$c->getCategoryByCID($_GET['cid']);
OR
$c = new something();
$cid = sanitizemeHARD($_GET['cid']);
$c->getCategoryByCID($cid); //Of course in this case, the func doesn't have sanitization built in
Its a question of policy that you set for the whole project.
I would prefer following the rule “Filter upon receiving” – i.e. at the point where external data is acquired.
This would avoid double-sanitizing in each object/method the data might pass through, and also makes easier to check the whole code for correct filtering.
So, in your example – the second case.