alt-web logo

Tips & Tutorials for Web Designers

Monday, July 27, 2015

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

If you stumbled on to this page from a search engine, I highly recommend first reading:
In Part 3 of this tutorial, we will add Error and Success reporting to our responsive contact form.  If you have been following along, this is the combined PHP & HTML5 code you should have in your document thus far.

 <?php
// NOTE: this page must be saved as a .php file.
// And your server must support PHP 5.3+ 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']);
         //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";
// 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 is not required so we don't need error message
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.';
        }
}
// 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
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bootstrap Form and PHP Script</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--Bootstrap-->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
.required {color:red; font-weight:bold}
.center-block {float:none}
.human {margin: 0 0 0 12px}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="col-md-8 center-block">
<h3>Responsive Contact Form</h3>
<p class="required small">* = Required fields</p>
<!--begin HTML Form-->
<form class="form-horizontal" role="form" method="post" action=" ">
<div class="form-group">
<label for="name" class="col-sm-3 control-label"><span class="required">*</span> Name:</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-3 control-label"><span class="required">*</span> Email: </label>
<div class="col-sm-9">
<input type="email" class="form-control" id="email" name="email" placeholder="you@domain.com">
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-3 control-label">Phone: </label>
<div class="col-sm-9">
<input type="tel" class="form-control" id="phone" name="phone" placeholder="(123) 456-7890">
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-3 control-label"><span class="required">*</span> Message:</label>
<div class="col-sm-9">
<textarea class="form-control" row="4" name="message" placeholder="Tell us your story"></textarea>

</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-3 control-label"><span class="required">*</span> Human Test:</label>
<div class="col-sm-4">
<h3 class="human">6 + 6 = ?</h3>
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6 col-sm-offset-3">
<button type="submit" id="submit" name="submit" class="btn-lg btn-primary btn-block">SUBMIT</button>
</div>
</div>
<!--end Form--></form>
<!--end col block--></div>
<!--end col--></div>
<!--end row--></div>
<!--end container--></div>
<!--Latest jQuery Core Library-->
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<!--Bootstrap-->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>



The form action attribute is empty.  If our script was in a separate file, we could call it with  action="some_script.php"  but since we have put our script directly into the contact page, we don't need to call a separate file.   Instead we will use PHP_SELF to execute this script.  For security reasons, we will filter html characters so hackers can't exploit this form by typing a bogus URL and code in the address bar. So here is the code:

<!--begin HTML Form-->
<form class="form-horizontal" role="form" method="post" action="
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">


Next, we need to add a placeholder for Bootstrap's Error or Success Alert messages to appear when the form is submitted.  Add this entire block under the opening <form> tag.

<!--when submit button is clicked, show results here-->
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">

<?php echo $result;?>
</div>
</div>


We also need to show the data values inside the form input fields and if data is missing, we will show the error message under the missing field inside <span> tags.  Let's start with the name input field.

<input type="text" class="form-control" id="name" name="name" placeholder="First & Last" value="<?php echo $name;?>">
<span class="required small"><?php echo $errName;?></span>


Repeat this for the remaining input fields - email, phone, message and human (bot-test).

<input type="email" class="form-control" id="email" name="email" placeholder="you@domain.com" value="<?php echo $email;?>">
<span class="required small"><?php echo $errEmail;?></span>



<input type="tel" class="form-control" id="phone" name="phone" placeholder="(123) 456-7890" value="<?php echo $phone;?>">
<span class="required small"><?php echo $errPhone;?></span>



<textarea class="form-control" row="4" name="message" placeholder="Tell us your story"><?php echo $message;?></textarea>
<span class="required small"><?php echo $errMessage;?></span>



<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer" value="<?php echo $human;?>">
<span class="required small"><?php echo $errHuman;?></span>


Completed Form

If you've followed my instructions to the letter, your form and processing script should be working properly when you upload it to your remote server and test it.  Pat yourself on the back for a job well done!

If it's not working, I suggest reviewing Part 1 and  Part 2  of this tutorial.

Should you require additional form input fields, make sure to add them to:
  • HTML form, 
  • the list of defined variables in your PHP script,
  • PHP error messages,
  • don't forget to include them in the $body of your receiving email.   
Also remember that PHP code is cAsE sEnSiTiVe.  So please be consistent.  To avoid critical code errors, use all small case letters without any spaces or special characters in your form IDs, names and variables.  Underscores_ and hyphens- are permitted. 

I hope you have enjoyed this 3-part introductory tutorial on creating a responsive contact form with Bootstrap and PHP code.  If you are so inclined:
  • DONATE via my PayPal button (Help feed the kitty) to the right,
  • g+ this on Google  
Thank you!

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