I tend to find you can sanitise/validate data as it comes in from GET, POST, etc. I never deal directly with $_GET or $_POST; I have to get it via a cleaner object and tell it what data type I’m expecting. Anything more specific than that (e.g. it needs to be a four digit int greater than 2000 and less then 3000) is done is more specific classes/functions.
It occurred to me though, should you write functions as though the scalar type has already been checked?
You could have:
function foo($int) {
$int = (int) $int;
// Do something
}
Or:
function foo($int) {
// Assume it's an int
// Do something
}
The first is leaner on code but, in theory, another programmer could pass an array to foo(); In this case, PHP would just issue a warning. If you check data types, etc on every function I’m thinking code will end up too bloated.
Is validating/sanitising twice “just to be on the safe side” bad practice? What is your procedure/policy?
I’d think it’s less good to validate twice, because it means code that logically belongs together is actually split. You can’t just look at your validation classes/functions and know if you’ve checked everything that needs to be checked, because you’re relying on some of those checks being done elsewhere. I’d think that the responsibilities of your cleaner object should be moved into the validation classes/functions. That is, your validation might check that it’s an int and that it’s four digits between 2000 and 3000. And with that logic consolidated, there’s no longer any need to re-check the data type elsewhere.