I have been trying to implement server validation to prevent blank emails in my contact us page, but I am not sure on how to do it in PHP, here is my code:
You can use filter for this; since you're using the passed email address as part of the mail()
operation, it's best to also validate:
$fields = filter_input_array(INPUT_POST, array(
'name' => FILTER_UNSAFE_RAW,
'email' => FILTER_VALIDATE_EMAIL,
'tel' => FILTER_UNSAFE_RAW,
'message' => FILTER_UNSAFE_RAW,
));
// check for missing fields
if (null === $fields || in_array(null, $fields, true)) {
// some or all fields missing
} elseif (in_array(false, $fields, true)) {
// some or all fields failed validation
} else {
// all fields passed validation
// use $fields['email'] as the email address
}
I've used FILTER_UNSAFE_RAW
for all fields except email, but perhaps there are better filters that apply.