logo Lee Johnson SEO

PHP Form with Validator

Finding a form falidator thats easy is always hard to find. This is just so easy. Add the form validator above the head of the page and then just add the form to the section of the page you want the form to be displayed.


<?
// form validator
$mailheader = "MIME-Version: 1.0" . "\r\n";
$mailheader .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
if ($_POST["submit"]) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$ip = $_SERVER['REMOTE_ADDR'];
$hostaddress = gethostbyaddr($ip);
// REMOVE [---] AND ADD YOUR EMAIL ADDESS
$to = '[---]';
// SUBJECT OF EMAIL TO BE SENT 
$subject = 'Website Enquiry';
$body ="From: $name\n\n E-Mail: $email\n\n Phone: $phone\n\n Message: $message\n\n IP Address: $ip";
// Check if name has been entered
if (!$_POST['name']) {$errName = 'Please enter your name';}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {$errEmail = 'Please enter a valid email address';}
// Check if phone has been entered
if (!$_POST['phone']) {$errPhone = 'Please enter your phone number';}
//Check if message has been entered
if (!$_POST['message']) {$errMessage = 'Please enter your message';}
//Check if simple anti-bot test is correct
if ($human !== 32) {$errHuman = 'Your anti-spam is incorrect';}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errPhone && !$errMessage && !$errHuman) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';}}}
?>

<!-- This is the form using bootstrap -->
<form class="form-horizontal" role="form" method="post" action="#contact">
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="phone" class="form-control" id="phone" name="phone" placeholder="Phone Number" value="<?php echo htmlspecialchars($_POST['phone']); ?>">
<?php echo "<p class='text-danger'>$errPhone</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control" rows="4" placeholder="Your Enquiry" name="message">
<?php echo htmlspecialchars($_POST['message']);?>
</textarea>
</div>
</div>
</form>