0
votes

We are receiving empty emails from our site contact form, and we don't know why. Our form is very simple and the validation is also not so advanced, but enough for our purpose.

We have 5 fields:

  • Name (text input)
  • mail (text input)
  • phone (text input)
  • reason (select, 3 values)
  • message (textarea)

Then with JS we validate all fields. Finally, with submit, we send the mail with php mail function:

<?php
$name = $_POST['name'];
$mail= $_POST['mail'];
$phone= $_POST['phone'];
$reason= $_POST['reason'];
$message= $_POST['message'];

$header = 'From: ' . $mail. " \r\n";
$header .= "X-Mailer: PHP/" . phpversion() . " \r\n";
$header .= "Mime-Version: 1.0 \r\n";
$header .= "Content-Type: text/plain";

$msg.= "Name: " . $name . " \r\n";
$msg.= "Mail: " . $mail. " \r\n";
$msg.= "Phone: " . $phone. " \r\n";
$msg.= "Reason: " . $reason. " \r\n";
$msg.= "Message: " . $message. " \r\n";

$for= "[email protected]";
$as= "Contact form";

mail($for, $as, $msg, $header);
?>

In general, works OK. But sometimes we receive an email with ALL (including reason... which is a select!) fields empty. Something like:

Subject: Contact form
Name:
Mail:
Phone:
Reason:
Message:

How can this be?

2
A code or some pieces should be great - Snake Eyes
the reason we need code you might be sending empty string in js overwritten variables - shareef
I don't have the code right now but I will have it soon. But, it only fails sometimes.... - legami
Select can be empty if user does not check any item. - Trinh Hoang Nhu
Also with selected="selected" ¿? I didn't know that. - legami

2 Answers

2
votes

Asumming you are sending the data through POST:

Have you considered that the action url may be directly accesed from the browser without any kind of POST data?. That would make all the "fields" empty.

If that's the case You can try a server validation in several ways:

  • Add a referer validation so that the url may only be accesed from the form url. Your can use $_SERVER['HTTP_REFERER'] for that purpose but keep in mind that may not always be available.
  • Find out if the data is sent. You can use isset for that purpose like in if(isset($_POST['name']) && isset($_POST['email']) in order to add a server validation. You can always do this $name=isset($_POST['name']) ? $_POST['name'] : 'no_name_entered' and have the email sent anyway.
  • Add a hidden input like "contacting" within your form and check if it's set server side: if(!isset($_POST['contacting'])) die('ERROR: Form not sent');

Anyway, keep in mind that most data you recieve can be tainted, even the ones sent through a select field.

2
votes

Create server side validation using php script.

Demostration

if($_POST['Name']=="") {
    $err = "Enter the name";
}
if($_POST['mail']=="") {
    .......
}

......
if($err=="") {
    //mail function
}
else {
    echo $err;
}