The Astoria Library Of The

Social Sciences

A modest collection available to the public






Scripts

PHP Contact Form with Validation

 

I've put together a very simply PHP contact form with validation for the form inputs. I have not included any styling, and I think even PHP novice will be able to modify the script without difficulty.

First, put the script below at the top of your page. This script will validate the inputs from your form. Remember, insert your email address and desired email subject line where indicated.

<?php

if(isset($_POST['submit_contact'])) {

//CHECK NAME
if(empty($_POST['flname'])) {
$err_name = "You must provide your name.";
}
else {
$flname = filter_var($_POST['flname'], FILTER_SANITIZE_STRING);
}

//CHECK EMAIL
if(empty($_POST['email'])) {
$err_email = "You must enter an email.";
}
elseif (!preg_match("/([w-]+@[w-]+.[w-]+)/",$_POST['email'])) {
$err_email = "You must enter a valid email.";
}
else {
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
}

//CHECK NAME
if(empty($_POST['msg'])) {
$err_msg = "You must include a message.";
}
else {
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
}

//IF NO ERRORS
if(!isset($err_name) && !isset($err_email) && !isset($err_msg)) {

//SEND EMAIL
$to = "xxx"; //<=== Your Email Here
$subject = "xxx"; //<=== Your Email's Subject Here
$message = "From: $flname n $msg";
$from = "$email";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);

$send_success = "Thanks for your interest! I'll be in touch soon.";

}

?>

Then, in the body, insert the validation message and the contact form.

<?php

if(isset($err_name) || isset($err_email) || isset($err_msg) || isset($send_success)) {
echo "<div id='error'>";
if(isset($err_name)) {echo $err_name."<br />";}
if(isset($err_email)) {echo $err_email."<br />";}
if(isset($err_msg)) {echo $err_msg."<br />";}
if(isset($send_success)) {echo $send_success."<br />";}
echo "</div>";
}

if(!isset($send_success)) {

?>

<form action="" method="post">

<p>Name</p>
<input type="text" name="flname" />
<p>E-mail</p>
<input type="text" name="email" />
<p>Message</p>
<textarea name="msg"></textarea>
<p></p>
<div style="text-align:center"><input type="submit" name="submit_contact" value="Send Message &raquo;" /></div>

</form>

<?php } ?>

That's all there is to it. I hope it helps you get your Web site off the ground!



Need Help? Want it customized?

I can install this script on your website or customize it to your specifications. Complete the form below and I'll be in touch to discuss your project.

E-mail