php Contact form script with validation

Creating a contact form using php is a simple thing that any one can do with basic php knowledge. This is a basic email contact form script and you can edit it to fit your needs.
Let first create the html form to get the inputs from the sender.

Contact.html

Here we submitting the form data to formprocess.php using “action” attribute. I have included a few general input fields that is name, email, subject and message in the form. You can add more inputs as you like.
Let create formprocess.php to accept the submitted data.

formprocess.php

if($_POST){

$name = $_POST['name']; //gets the entered name
$email = $_POST['email']; //gets the entered email address
$subject = $_POST['subject']; //gets the subject
$message = $_POST['message']; //gets the entered message
$headers = "From: $email \n"; //Set from email address

$to = "example@yourdomain.com"; //Set your to email address
//validating the fields if any empty
if($name != "" && $email != "" && $subject != "" && $message != ""){
mail($to,$subject,$message,$headers); //calling php mail function
} else
{
echo "Please fill in all fields and submit again!";
}
}

In our first line of code we have “if($_post)” to avoid executing the code without the form submitted. All the remaining codes are simple to read and the short comments will explain you what it do.

52 Downloads