I have a basic form with a dozen fields (I would take 3 for example):
<input type="text" name="user_first_name" class="form-control" pattern="[A-Za-z-]+" required />
<input type="text" name="user_last_name" class="form-control" pattern="[A-Za-z-]+" required />
<input type="tel" name="user_phone" class="form-control" />
...
Only the phone number can be empty, the last name and first name are obligatory and can contain only letters and dashes (the technical constraints were imposed on me by our old ERP)
I created a function to clean up all my fields that looks like this:
public function sanitizeInfo($user_first_name, $user_last_name, $user_phone) {
$user_first_name = preg_replace('/[^A-Za-z-]/', '', $user_first_name);
$user_last_name = preg_replace('/[^A-Za-z-]/', '', $user_last_name);
$user_phone = (isset($user_phone) and !empty($user_phone)) ? preg_replace('/[^A-Za-z0-9+-.)(]/', '', $user_phone) : NULL;
$array = array(
"first_name" => $user_first_name,
"last_name" => $user_last_name,
"phone" => $user_phone
);
return $array;
}
In my PHP script I make this first check:
$fields = array('user_first_name', 'user_last_name');
$error = FALSE;
foreach ($fields as $fieldname) {
if(!isset($_POST[$fieldname]) or empty($_POST[$fieldname])) {
$error = TRUE;
$message = 'err';
}
}
if (error === TRUE) {
echo "Error !"
} else {
$info = sanitizeInfo($_POST['user_first_name'], $_POST['user_last_name'], $_POST['user_phone']);
...
** QUERY **
}
I want to check, before sending this in database, that the fields are not empty (only the telephone number can be NULL)
But the problem right now is that I do not know if my non-required fields exist and especially my sanatizeInfo
function is problematic because it allows to put empty fields in database
Example:
The user enters "!! -" as firstname and the sanitizeInfo
function returns "" because the preg_replace
to delete these characters
How to avoid this?