I am trying to set up a Contact form on my website that will:

  1. Gather the user's info
  2. Validate that none of the required fields are empty, if they are, then redirect the user back to the contact form page to fill in the empty field
  3. Send it to my email address
  4. Display a thank you page when it is submitted successfully

My Contact form does everything as expected except when I intentionally leave one of the required fields empty, it still sends the email anyways and shows the Thank You page. Here is the code for my contact.htm and process.php.

<form method="post" action="process.php">			
   <table style="width: 60%" class="auto-style3" cellspacing="3">
    <tr>
     <td class="auto-style4" style="width: 160px"><label>Company</label></td>
     <td style="width: 145px" class="auto-style6">* Required</td>
    </tr>
    <tr>
     <td style="width: 160px"><input name="Company" type="text" style="background-color:silver" /></td>
     <td style="width: 145px">&nbsp;</td>
    </tr>
    <tr>
     <td style="width: 160px">&nbsp;</td>
     <td style="width: 145px">&nbsp;</td>
    </tr>
    <tr>
     <td class="auto-style4" style="width: 160px"><label>First Name</label><span class="auto-style6">*</span></td>
     <td class="auto-style4" style="width: 145px"><label>Last Name</label><span class="auto-style6">*</span></td>
    </tr>
    <tr>
     <td style="width: 160px"><input name="FirstName" type="text" style="background-color:silver" /></td>
     <td style="width: 145px">
     <input name="LastName" type="text" style="background-color:silver; width: 145px;" /></td>
    </tr>
    <tr>
     <td style="width: 160px">&nbsp;</td>
     <td style="width: 145px">&nbsp;</td>
    </tr>
    <tr> 
     <td class="auto-style4"style="width: 160px"><label>Phone<span class="auto-style6">*</span></label></td>
     <td class="auto-style4" style="width: 145px"><label>Email<span class="auto-style6">*</span></label></td>
    </tr>
    <tr>
     <td style="width: 160px"><input name="Phone" type="text" style="background-color:silver" /></td>
     <td style="width: 145px"><input name="Email" type="text" style="background-color:silver; width: 145px;" /></td>
    </tr>
    <tr>
     <td style="width: 160px">&nbsp;</td>
     <td style="width: 145px">&nbsp;</td>
    </tr>
    <tr>
     <td class="auto-style4" style="width: 160px"><label>Message<span class="auto-style6">*</span></label></td>
     <td style="width: 145px">&nbsp;</td>
    </tr>
    <tr>
     <td colspan="2">
     <input name="Message" type="text" style="background-color:silver; width: 310px; height: 100px;" /></td>
    </tr>
    <tr>
     <td style="width: 160px">&nbsp;</td>
     <td style="width: 145px"> </td>
    </tr>
    <tr>
     <td class="auto-style5" colspan="2">
     <input name="Submit1" type="submit" value="submit" />
     <input type="hidden" name="form_submitted" value="true"/> 						
    </tr>
  </table>
</form>

And here is my process.php

<?php
  ob_start();

// Form Variables
global $_POST;
$Company   = stripslashes($_POST["Company"]);
$FirstName = stripslashes($_POST["FirstName"]);
$LastName  = stripslashes($_POST["LastName"]);
$Email     = stripslashes($_POST["Email"]);
$Phone     = stripslashes($_POST["Phone"]);
$Message   = stripslashes($_POST["Message"]);

//Handling Errors
print '<style type="text/css" media="screen">
	  .error {color:red}
	  </style>';

//Form validation
if (!isset($_POST['submitted'])) {
 }
if (empty($_POST['FirstName'])) {
 	header ("Location: contact.htm");
	print '<p class="error">Please enter your First Name!</p>';
	}
	
if (empty($_POST['LastName'])) {
	header ("Location: contact.htm");
	print '<p class="error">Please enter your Last Name!</p>';
	}

if (empty($_POST['Phone'])) {
	header ("Location: contact.htm");
	print '<p class="error">Please enter your Phone Number!</p>';
	}
	
if (empty($_POST['Email'])) {
	header ("Location: contact.htm");
	print '<p class="error">Please enter your Email Address!</p>';
	}

if (empty($_POST['Message'])) {
	header ("Location: contact.htm");
	print '<p class="error">Please enter a brief message!</p>';
	} 


// The email address to send the form submission to
$to = "email@mydomain.com";

// The subject of the email you received
$subject = " Contact Form Submission";

// This is to send the information as html - and include the senders email address as the "from" in the
// form submission to make it easy for you to simply hit "reply" and contact them back.
$headers = "From: $email\n" . "MIME-Version: 1.0\n" .
    "Content-type: text/html; charset=iso-8859-1";

// The message you will receive.  This is in html so its real easy to customize how you want it to look.
$message = "<table width='600' border='0' align='left' cellpadding='0' cellspacing='0' bgcolor='#F9F9F9' style='border: 1px solid #333333;'>
  <tr> 
    <td> <div align='center'> </div>
      <table width='600' border='0' cellpadding='8' cellspacing='0'>
        <tr> 
          <td><table width='400' border='0' align='center' cellpadding='8'   cellspacing='0' bgcolor='#FFFFFF' style='border: 1px dashed #666666;'>
              <tr align='left' valign='top' bgcolor='#EFEFEF'> 
                <td width='96'><strong><font size='2' face='Arial, Helvetica, sans-serif'>Company:</font></strong></td>
                <td width='278'><font color='#5E0000' size='2' face='Arial, Helvetica, sans-serif'>$Company</font></td>
              </tr>
              <tr align='left' valign='top' bgcolor='#FFFFFF'> 
                <td width='96'><strong><font size='2' face='Arial, Helvetica, sans-serif'>First Name:</font></strong></td>
                <td width='278'><font color='#5E0000' size='2' face='Arial, Helvetica, sans-serif'>$FirstName</font></td>
              </tr>
              <tr align='left' valign='top' bgcolor='#EFEFEF'> 
                <td width='96'><strong><font size='2' face='Arial, Helvetica, sans-serif'>Last Name:</font></strong></td>
                <td width='278'><font color='#5E0000' size='2' face='Arial, Helvetica, sans-serif'>$LastName</font></td>
              </tr>
              <tr align='left' valign='top' bgcolor='#FFFFFF'  > 
                <td><strong><font size='2' face='Arial, Helvetica, sans-serif'>Phone:</font></strong></td>
                <td><font color='#5E0000' size='2' face='Arial, Helvetica, sans-serif'>$Phone</font></td>
              </tr>
              <tr align='left' valign='top' bgcolor='#EFEFEF'> 
                <td><strong><font size='2' face='Arial, Helvetica, sans-serif'>Email:</font></strong></td>
                <td><font color='#5E0000' size='2' face='Arial, Helvetica, sans-serif'>$Email</font></td>
              </tr>
              <tr align='left' valign='top' bgcolor='#FFFFFF' > 
                <td><strong><font size='2' face='Arial, Helvetica, sans-serif'>Message:</font></strong></td>
                <td><font color='#5E0000' size='2' face='Arial, Helvetica, sans-serif'>$Message</font></td>
              </tr>
            </table></td>
        </tr>
      </table></td>
  </tr>
</table>";

// Confirmation email
$to2 = "$email";
$subject2 = "Thank You For Contacting Us";
$headers2 = "From: <email@mydomain.com>\n";
$message2 = "Hi $FirstName. Thank you for contacting us.  We have received your form submission and will be in contact with you shortly";

// A quick check to make sure the email field isnt being used to hijack or maliciously attack your server
if (preg_match(' /[\r\n,;\'"]/ ', $_POST['email'])) {
// Give them an error page if malicious code is found
header("Location: error.html");
}
// If all is well ... Send the email
mail($to,$subject,$message,$headers);
// and send the confirmation message to the sender
mail($to2,$subject2,$message2,$headers2);
// And go to the Thank You page
header ("Location: thank_you.htm");
?>

I have tried for the last 3 days to catch my mistake without any luck. Any help with the correct syntax would be greatly appreciated!

One thing that website designers sometimes do, is process the form on a separate PHP file. Just put all the code on the conact page, so it doesn't have to go to an entirely separate page if the form is invalid. Of course, if the form is valid, then you would direct the user to a success page.

This is the validation I use on my contact forms. It first checks to see if any of the values are blank, if at least one is, it goes on to see which one and puts the error message on the $errorMsg variable.

Since all the code is processed on the same PHP contact page (<form action="contact.php">), the $errorMsg variable can be printed wherever you like.
Above my form I have this to display my errormsg if there is one:

<?php
	if ($errorMsg) {
	  echo "<div class=\"warning\">";
		print "$errorMsg";
	  echo "</div><!-- End Warning -->";
	  }
	?>

Also note the dot equals (.=) for every $errorMsg. That will append that value onto the variable with the existing ones.

if((!$name || !$email || !$message)) {

	$errorMsg = 'Please Fill in the following fields:<br>';
	
	if (!$name) {
		$errorMsg .= 'Your Name<br>';
		}

	if (!$email) {
		$errorMsg .= 'Your Email<br>';
		}

	if (!$message) {
		$errorMsg .= 'Your Message<br>';
		} else {// If no errors, process the form

Tell me if it works :)

It is always a good idea to use PHP for form validation. But you can as a add on consider JavaScript validation, to save server from some of the unnecessary processing.

Something like this can solve your problem, but is not the solution for your problem

<form action="process.php" method="post" name="register_form" onSubmit="return validate_form();"> 
.
.

use exit after this line in your program.

header ("Location: contact.htm");
exit;

or better still use a $flag variable to indicate if everything is correct.
set it to false after if(empty) and enclose your mail in if($flag)

Vinayak

You can use Javascript validation, but it is not as secure because you can easily disable javascript. You could use both for a user friendly jquery and ajax experience :)

Member Avatar for diafol

OK, some valid responses, but the reason why you get an email and a thank you page is because they're not controlled (i.e. no if/else structures). There's nothing to stop the email or thankyou, unless there's a nasty email address.

Also

if (!isset($_POST['submitted'])) {
 }

is closed - nothing in it! - it doesn't enclose the other POST checks. So the post checks will happen regardless of whether a form is sent to the page.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.