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:
Try to put a submit input <input type="submit" name="sub" value="Submited">
inside your form
when it's clicked.
<?php
if (isset($_POST['sub']) {
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_tel = $_POST['cf_tel'];
$field_message = $_POST['cf_message'];
if (empty($field_name) && ....)
{
exit('Field name is empty');
}
.....
just test the variable for "emptiness" and exit early. Something like this:
if(empty($field_email)) {
// maybe show the user a reason why this was rejected...
return;
}
You probably want to do this for just about all the input fields.
In addition, you can use JavaScript (jQuery has some nice plugins) to prevent the user from submitting invalid data in the first place. This won't remove the need to do it server side (since they can just disable JS, or someone malicious might intentionally bypass this measure), but it can make it a more user friendly experience.
Before your $mail_to..
You can validate the _POST/_GET first on server side.
<?php
if (empty($field_name) && empty($field_email) && empty($field_tel) && empty($field_message)) {
echo 'Please correct the fields';
return false;
}
?>
Alternatively, you can validate first on the client-side. It will save you time and resources.
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.