PHP Contact Form w/ required fields still sends blank forms

I’m working on a client site that includes 2 basic PHP forms. They’re simple contact forms that call a contact.php file and includes some code to require some fields have data entered before the form can successfully be submitted. The complete code is:

$to = "";
$subject = "Website Contact form submission";
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$company = $_REQUEST['company'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
$headers = "From: $email";
$body = "From: $name \
 Company: $company \
 Email: $email \
 Phone: $phone \
 Message: $message";
if (empty($email) || empty($name) || empty($message)) { echo "<script language=javascript>window.location = '/contact-fail/';</script>"; die();}
$sent = mail($to, $subject, $body, $headers) ;
$sent = mail($to, $subject, $body, $headers) ;
{echo "<script language=javascript>window.location = '/contact-sent/';</script>";}
{echo "<script language=javascript>window.location = '/contact-fail/';</script>";}

And it appears to work. The form submits the data to an email address, so I tested it using my own email address and blank forms don’t send any data.

Since I changed the recipient email address to the client’s and launched the updated php files, the client tells me they’re still getting blank forms coming through. Completely blank, no data in any field. How is that possible?

Is there some way that the “die” can be bypassed and the form still sent despite the if(empty) code? Or is there a better way to prevent blank form submissions in php?

A blank space is not empty :eek: spaces and tab characters would pass. You could use PHP: strlen - Manual or even better a regular expressions.

This example only allows alphanumeric, some punctuation (. , ; : - ! ? &) and between 10 and 200 characters.

preg_match("/^[a-z0-9\\s\\.\\,\\;\\:\\-\\!\\?\\&]{10,200}\\z/i", $subject)

or you could trim() the fields.

You could but the point is to be more specific about what input is allowed. I could just fill all the fields with a dot and it would pass.

You could fill the fields with 10 dots and it’d pass your preg_match too. shrug

The regular expression was a poor example really. I mealy meant to highlight how easily you could validate input with a regular expression.

You can’t make it impossible to enter rubbish information but that doesn’t mean do nothing. If you can enter anything, you can also enter HTML or JavaScript. Also a sender may accidentally enter an invalid phone number or email address; how can you respond to them if you have incorrect information. Validation can help to prevent this from happening.

This, btw, is an age old discussion that never has an answer :wink:

But yes, all of the solutions provided have weaknesses; they will all prevent ‘blank’ input, however.

I’m assuming the duplication in the OP’s code for $sent is a copy/paste error, btw? Dont want to send the same mail twice, surely.