Obviously you should validate ALL user input data on the server side. I'm just curious what is considered "proper" input validation and the order of which it should be done.
As of right now (and recent projects past) I have done it this way:
Get the user input, instantiate the object, and call the method:
if(isset($_POST['addCat'])) {
$db = new DBConnection;
$categories = new Category($db);
if($categories->insert_cat($_POST['name']) === TRUE) {
echo "Category Inserted Successfully!";
}
}
The method called from the instantiated object which:
1. escapes the user input
2. istantiates the data_validation object (see the validation object below)
class Categories {
public function insert_cat($catName) {
$catName = $this->mysqli->real_escape_string($catName);
$validate = new data_validation;
if(!($validate->validate_string($catName))) {
echo "Invalid characters found in category name";
die();
}
$query = $this->mysqli->query("INSERT INTO categories(name) VALUES ('".$catName."')");
if($query === false) {
printf("Error: %s\n", $this->mysqli->error);
die();
} else {
return true;
}
}
}
data_validation class which:
1. trims the data
2. matches the data to a regular expression
3. returns the data to the insert_cat method for database insertion
class data_validation {
public function validate_string($data) {
// Remove excess whitespace
$data = trim($data);
if ( preg_match("/^[0-9A-Za-z \.\-\'\"]+$/", $data) ) {
return true;
} else {
//return 'Not a valid string';
return false;
}
}
}
So basically in short my question is: Is it proper to first escape the data, then trim it, then compare it to a regular expression, then add htmlentites()
or something of those sorts to preserve any formatting or should it be done in a different order?
Any tips to improve my security habits are more than welcome!