I’ve made a PHP contact form for a client and they’ve come back to me saying they are receiving blank emails like this:
From:
E-Mail:
Message:
I’ve put JavaScript validation in place which successfully refuses a blank form when I submit the form in the standard way.
- What could be happening? Are we talking something malicious or stupid?
- What extra checks should I put in place? Are PHP checks a standard thing?
Code included below. Thanks in advance 🙂
JS validation:
$("form#submit").submit(function() {
var custname = $('#custname').attr('value');
var custemail = $('#custemail').attr('value');
var custmessage = $('#custmessage').attr('value');
if (custname==null || custname=="" || custemail==null || custemail=="" || custmessage==null || custmessage=="") {
alert("Please fill out the whole form");
return false;
}
PHP mailer page:
<?php
$to = "name@email.com";
$subject = "Message from website";
$name_field = htmlspecialchars(trim($_POST['custname']));
$email_field = htmlspecialchars(trim($_POST['custemail']));
$message = htmlspecialchars(trim($_POST['custmessage']));
$body = "From: $name_field\n E-Mail: $email_field\n Message: $message";
mail($to, $subject, $body);
?>
In the PHP mailer page, you can write something like:-
This above code mostly covers the server side validation, along with the Email Validation. However, you can also provide more stringent Email Validation checks than the one which I have used, and Captcha checking as well.
Although, the above code has served me well for quite some years, it must be mentioned that this snippet is not the last & full-proof, as I have not used any filter / sanitization (like what WordPress or other CMSs do) for all the user inputs. But nevertheless, it should get you well started with Google when dealing with user inputs.
You can also check out some of the below links for filter / sanitize:-
Hope it helps.