Validation on contact form not working

Sorry for bashing this one to death yet I want to implement a simple AJAX/PHP contact form and I have it nearly working except for the PHP validation.


<?php
// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = 'XXX.net';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: XXX.net' . "\\r\
";

//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
echo "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
echo "No message was entered.<br>Please include a message.<br>";
}

if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}else{
echo "Invalid email! <br/>Please provide a correct email address for us to contact you.";
}

?>

The email invalid error works yet the

if (empty($message) && empty($email))

does not… Sure its a syntax problem.

The AJAX for reference is;


<script type="text/javascript">
$(document).ready(function(){

$('#submit').click(function(){

$.post("contact/send.php", $("#mycontactform").serialize(),  function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;

});

});
</script>

Turn on error reporting at the top of the file, temporarily.


<?php 

//  turn this off or rm the lines before publishing
error_reporting(E_ALL);
ini_set("display_errors", 1);


// fail first before evoking any more variables ...

$errors = array();

if( !isset($_POST['email']) || empty($_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) ){
$errors[] = "Missing or invalid email";
}

// ditto with the other expected incoming vars

if( !isset($_POST['message']) || empty(trim($_POST['message']))){
$errors[] = "Missing a message";
} 

if($errors){
 echo 'You had some errors:<br />';

  foreach($errors as $error)
    echo $error . '<br />';

  exit();  // or relocate, or show the form again
}

// now get on and do some emailing

I started replying but ended up re-writing the top part of your script. Hopefully there is something there you can use. All untested btw.

Maybe just adding the error reporting lines to the top of your script would show up something on your existing script.

You’d probably want to do some more filtering and escaping.

Of course fish the error… i’ll do this with thanks!