alt-web logo

Monday, July 27, 2015

Responsive Contact Form with Bootstrap 3.2 and PHP (Part 2)

If you stumbled on to this blog from a search engine, I highly recommend reading Part 1 of this tutorial.  It discusses Bootstrap and the necessary structure for our HTML5 Contact Form.

In this tutorial, we will create a PHP form processing script for our contact form.  As you'll remember from the previous tutorial, these are the form fields we have created so far:

name (required)
email (required)
phone (optional)
message (required)
human (required, math problem)

First, we will add this PHP code above our contact form's document type declaration or DTD.

<?php
// NOTE: this page must be saved as a .php file.
// And your server must support PHP 5.3+ and PHP Mail().
// Define variables and set to empty values
$result = $name = $email = $phone = $message = $human = "";
$errName = $errEmail = $errPhone = $errMessage = $errHuman = "";
    if (isset($_POST["submit"])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $message = $_POST['message'];
        $human = intval($_POST['human']);
}
//end form processing script
?>


Next, we will tell the script where the form data is coming from (an address on your web server)  and where it should be sent (your email address). Then we define which form fields should be included in the email you receive. Insert this code below the $human = intval($_POST['human']); code above.

        //valid address on your web server
        $from = 'webmaster@yourdomain.com';
        //your email address where you wish to receive mail
        $to = 'you@yourdomain.com';
        $subject = 'MESSAGE FROM YOUR WEB SITE';
        $headers = "From:$from\r\nReply-to:$email";
        $body = "From: $name\n E-Mail: $email\n Phone: $phone\n Message: $message";

}
//end form processing script
?>


Next, we need to validate our form fields to ensure they are not empty and create some error messages.  We want to ensure the email field is in a valid format so we will use the PHP email filter.  Then we will create a solution value for the simple math problem.  Spambots can't do math but humans can.  This will keep spambots from submitting your form.

// Check if name is entered
if (empty($_POST["name"])) {
$errName = "Please enter your name.";
} else {
    $name = test_input($_POST["name"]);
}
// Check if email is entered
if (empty($_POST["email"])) {
$errEmail = "Please enter your email address.";
} else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is valid format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $errEmail = "Invalid email format.";
    }
}
// Check if phone is entered although it's not required so no error message is needed
if (empty($_POST["phone"])) {
$phone = "";
} else {
    $phone = test_input($_POST["phone"]);
}

//Check if message is entered
if (empty($_POST["message"])) {
$errMessage = "Please enter your message.";
} else {
    $message = test_input($_POST["message"]);
}

//Check if simple anti-bot test is entered
if (empty($_POST["human"])) {
$errHuman = "Please enter the sum.";
} else {
     if ($human !== 12) {
     $errHuman = 'Wrong answer. Please try again.';
        }
}
//end form processing script
?>


The next step is to test_input and sanitize it.  We don't want human hackers or robots injecting unwanted garbage or exploiting our forms so we trim white spaces,  strip slashes & html special characters and finally sanitize data with a PHP filter.  See here for more on PHP Sanitize Filters.

}
   //sanitize data inputs   
   function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   $data = (filter_var($data, FILTER_SANITIZE_STRING));
   return $data;
}
//end form processing script
?>


So what's left?  We need to give users some feedback.  Since we're using Bootstrap, we will rely on the ready-made Bootstrap Alert classes and Glyphicons for our form submission Success and Error messages.  We will insert this code just above the test_input sanitizing function above.

// If there are no errors, send the email & output results to the form
if (!$errName && !$errEmail && !$errPhone &&  !$errMessage && !$errHuman) {
    if (mail ($to, $subject, $body, $from)) {
        $result='<div class="alert alert-success"><h2><span class="glyphicon glyphicon-ok"></span> Message sent!</h2><h3>Thank you for contacting us. Someone will be in touch with you soon.</h3></div>';
    } else {
        $result='<div class="alert alert-danger"><h2><span class="glyphicon glyphicon-warning-sign"></span> Sorry there was a form processing error.</h2> <h3>Please try again later.</h3></div>';
       }
    }
}
   //sanitize data inputs   
   function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   $data = (filter_var($data, FILTER_SANITIZE_STRING));
   return $data;
}
//end form processing script
?>


OK. That's it for the PHP script. In Part 3 of this tutorial, we will go back to the HTML code and add Error and Success reporting to our contact form.

Part 1 - Creating HTML5 doc type with Bootstrap Contact Form
Part 2 - Creating the PHP Script
Part 3 - Creating Error & Success Reporting in the Contact Form