onsa
12/17/2016 - 4:00 PM

Simple contact form with Bootstrap

Simple contact form with Bootstrap

<form method="post" action="parentPage.php">
  <div class="form-group<?php if ($_POST && $_POST['name'] == '') {echo " has-error";} ?>"> <!-- add validation colour -->
    <div>
      <input type="text" name="name" class="form-control" id="email" placeholder="Your name" value="<?php echo $_POST['name']?>"> <!-- inject data submitted earlier -->
    </div>
  </div>
  <div class="form-group<?php if ($_POST && $_POST['email'] == '') {echo " has-error";} ?>">
    <div>
      <input type="email" name="email" class="form-control" id="email" placeholder="Your Email address" value="<?php echo $_POST['email']?>">
    </div>
  </div>
  <div class="form-group<?php if ($_POST && $_POST['message'] == '') {echo " has-error";} ?>">
    <div>
	  <textarea name="message" class="form-control" rows="3" placeholder="Your message"><?php echo $_POST['message']?></textarea>
    </div>
  </div>
  <div class="form-group">
    <div class="pull-right">
      <button type="submit" class="btn btn-default">Send</button>
    </div>
  </div>
</form>


<?php
// validate and submit
	if ($_POST) {
		if ($_POST['name'] == '' || $_POST['email'] == '' || $_POST['message'] == '') {
			echo "<span ID='error-message'>Please, fill in all three fields above.</span>";
		} else {
			$to = "example@host.com";
			$subject = 'New Message from '.$_POST['name'];
			$body = $_POST['message']."\r\n\r\n---\r\n\r\nThis is an automated e-mail sent from www.example.com.";
			$headers = "From: ".$_POST['email']."\r\n"."Reply-To: ".$_POST['email'];
			if (mail ($to, $subject, $body, $headers)) { 
				echo "<span ID='success-message'>Thank you for your interest. We will be in touch with you shortly.</span>";
			} else { 
				echo '<p>An error has occurred. Please, try again.</p>';
			}
		}
	}
?>