The best approach is to define data-type for each input, not just globally filter all input data as you proposed. for example:
Consider these fields:
Name:
E-Mail:
Age:
Country:
Address:
Phone Number:
Plain text (textarea):
file (file upload):
Now, if you want to secure these fields, you have to deal with each of them individually.
1- Name: define maximum character length and data type (format), usually Name consists of only (A-z and space) and sometimes one single quota ('), or a dot (.) will be there if someone entered a title like Eng. Mr.
now, lets check that field, consider
<?php
$name = $_POST['name'];
$name_max_length = 30;
$name_min_length = 5;
$name_pattern = "/[a-zA-Z'\.\ ]{$name_min_length, $name_max_length}/";
if(!preg_match($name_pattern, $name)){
$error[] = "Please enter valid character for name field";
}else{
//lets now filter it for safe input
//above check not passes any kind of XSS, but it passes SQL injection
//we need to clear it from SQL injection
$name = htmlentities($name, ENT_QUOTES);
//ENT_QUOTES: Will convert both double and single quotes.
}
?>
2- Age: it must be integer, you can simply check it with built-in PHP function:
<?php
$age = $_POST['age'];
if(!is_int($age)){
$error[] = "Please enter valid number in Age field";
}
?>
3- Plain text: again, use htmlentities($name, ENT_QUOTES)
4- File upload:
- Check file extension, you have to create list of white-extensions and then compare uploaded file extension with white list for example:
<?php
$extensions = array('png', 'jpeg', 'gif');
if(!in_array($current_file_ext, $extensions)){
$error[] = "Please select valid file type! (".implode(", ", $extensions);
}
?>
Finally, before entering these data, check $error which an array if such error occured
<?php
if(count($error) > 0){
//means $error contains errors
//print error values
}else{
//start inserting your data into database
}
?>