Reputation: 171
I'm doing a security audit on a fairly large php application and was wondering where I should include my user-input validation.
Should I validate the data, then send the clean data off to the back-end functions or should I rely on each function to do it's own validation? Or even both?
Is there any standard or best-practice for this sort of thing?
Currently the app does both inconsistently and I'll like to make things more consistent.
Upvotes: 8
Views: 1220
Reputation: 11068
It depends on the scope/definition of the application. But traditionally, your functions are used in may places $object->doSomething() does just that. By relying on validation in there, you prevent the ability to doSomething() of your OWN acccord, ya know?
Too, if you keep validation outside you can easily manage it. No need to hunt it down in that particular internal function. Keep it OOP, but more like
$data = $validator->sanitizeSomething($data); $object->doSomething($data);
this keeps your validation rules separate and easy to manaage as well as your internal functions.
To elaborate, say you have a db object that adds an array to the table:
class db {
function addRow($table, $associativeArray) {
// primitive i know, just an example
}
}
would you want your validation in there?
function addRow($table, $associativeArray) {
if( isset( $assiciativeArray['description'] ) {
// validate
}
}
would be silly - you'd want that in the object you're working in
class product {
function update() {
if( $this->validate() ) {
$this->db->addRow($this->toArray()); // or something, you get the idea, ya?
}
}
function validate() {
if( $this->description != "") {
return true;
}
return false;
}
}
Upvotes: 3
Reputation: 18798
Validating at the backend is like screening passengers after they have boarded the plane. The whole point of validation is to prevent injecting elements that might choke up your app. So you must validate before you enter the gate :)
Upvotes: 3
Reputation: 2462
Both is the better answer. Data validation should happen in every function that will be handling the data to avoid the problem of Hope Driven Development (HDD)
Upvotes: 7
Reputation: 91963
You should definitely validate the data from the outside as soon as possible. Depending on the architecture, backend validation inside the responsible functions can be a second step, but don't depend on backend validation but validate the data when it comes in to your application.
The pros with validation inside functions as a complement to the previous validation is that it's easier (and safer) to maintain the system because (sloppier) developers after you can't break the application. If you have an application with plugin support, e.g. for third party plugins, safe functions is a must also.
Upvotes: 7
Reputation: 7150
I think if you can do both, and time / resources are not an issue, why not?
Upvotes: 3