Contact form of websites led user to communicate with website owners. This shows a genuine or loyal behavior of an organization towards its customers. Here we bring up in front of you the PHP contact form with validation feature.
In our previous blogs, we have applied JavaScript and jQuery codes on the contact form. Now, this tutorial emphasizes on applying PHP validations and mail() function over contact form.
Here, our PHP validation includes the following steps:
- Checking for empty fields.
- Checking for data filtration.
- Input comparison with Regular expression.
- First, we used PHP empty() function to check for empty fields.
if (empty($_POST["name"]))
{
echo "Name is required";
}
- Second, we pass the non empty value to a user defined function test_input($data) to filter user input.
// Function for filtering input values.
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
- Third, we applied preg_match() function to the above filtered value to get user input in correct format based on regular expression.
preg_match("/^[a-zA-Z ]*$/",$_POST['name']) // For a name or other text fields.
preg_match("/([w-]+@[w-]+.[w-]+)/",$_POST['email'])// For email field.
And at the end, we mail user input message using PHP mail () function in such a way that the sender will also get the copy of his mail.
mail("[email protected]",$msg, $header);
Watch our live demo or download our codes to use it.
Complete HTML and PHP codes are given below.
PHP file: contact_form.php
Given below our complete HTML contact form.
<?php include 'validation.php';?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Contact Form with Validation</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Contact Form with Validation</h2>
<form method="post" action="contact_form.php">
<label>Name :</label>
<input class="input" type="text" name="name" value="">
<span class="error"><?php echo $nameError;?></span>
<label>Email :</label>
<input class="input" type="text" name="email" value="">
<span class="error"><?php echo $emailError;?></span>
<label>Purpose :</label>
<input class="input" type="text" name="purpose" value="">
<span class="error"><?php echo $purposeError;?></span>
<label>Message :</label>
<textarea name="message" val=""></textarea>
<span class="error"><?php echo $messageError;?></span>
<input class="submit" type="submit" name="submit" value="Submit">
<span class="success"><?php echo $successMessage;?></span>
</form>
</div>
</div>
</body>
</html>
PHP file: validation.php
In the below script, we validate all fields and then mail the message using PHP mail() function. Also, the sender will get the copy of his mail.
<?php // Initialize variables to null.
$name =""; // Sender Name
$email =""; // Sender's email ID
$purpose =""; // Subject of mail
$message =""; // Sender's Message
$nameError ="";
$emailError ="";
$purposeError ="";
$messageError ="";
$successMessage =""; // On submittingform below function will execute.
if(isset($_POST['submit'])) { // Checking null values in message.
if (empty($_POST["name"])){
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]); // check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
} // Checking null values inthe message.
if (empty($_POST["email"]))
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
} // Checking null values inmessage.
if (empty($_POST["purpose"]))
{
$purposeError = "Purpose is required";
}
else
{
$purpose = test_input($_POST["purpose"]);
} // Checking null values inmessage.
if (empty($_POST["message"]))
{
$messageError = "Message is required";
}
else
{
$message = test_input($_POST["message"]);
} // Checking null values inthe message.
if( !($name=='') && !($email=='') && !($purpose=='') &&!($message=='') )
{ // Checking valid email.
if (preg_match("/([w-]+@[w-]+.[w-]+)/",$email))
{
$header= $name."<". $email .">";
$headers = "FormGet.com"; /* Let's prepare the message for the e-mail */
$msg = "Hello! $name Thank you...! For Contacting Us.
Name: $name
E-mail: $email
Purpose: $purpose
Message: $message
This is a Contact Confirmation mail. We Will contact You as soon as possible.";
$msg1 = " $name Contacted Us. Hereis some information about $name.
Name: $name
E-mail: $email
Purpose: $purpose
Message: $message "; /* Send the message using mail() function */
if(mail($email, $headers, $msg ) && mail("[email protected]", $header, $msg1 ))
{
$successMessage = "Message sent successfully.......";
}
}
else
{ $emailError = "Invalid Email";
}
}
} // Function for filtering input values.function test_input($data)
{
$data = trim($data);
$data =stripslashes($data);
$data =htmlspecialchars($data);
return $data;
}
?>
CSS File: style.css
Styling HTML elements.
/* Below line is used for online Google font */
@import url(http://fonts.googleapis.com/css?family=Raleway);
h2
{
background-color: #FEFFED;
padding: 15px 35px;
margin: -10px -50px;
text-align:center;
border-radius: 10px 10px 0 0;
}
hr
{
margin: 10px -50px;
border: 0;
border-top: 1px solid #ccc;
}
span
{
color:red;
}
div.container
{
width: 960px;
height: 610px;
margin:35px auto;
font-family: 'Raleway', sans-serif;
}
div.main
{
width: 350px;
padding: 10px 50px 30px;
border: 2px solid gray;
border-radius: 10px;
font-family: raleway;
float:left;
}
input[type=text],textarea
{
width: 97.7%;
height: 34px;
padding-left: 5px;
margin-bottom: 5px;
margin-top: 5px;
border: 2px solid #ccc;
color: #4f4f4f;
font-size: 16px;
border-radius: 5px;
}
textarea
{
resize:none;
height:80px;
}
label
{
color: #464646;
text-shadow: 0 1px 0 #fff;
font-size: 14px;
font-weight: bold;
}
.submit
{
padding: 10px;
text-align: center;
font-size: 18px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 2px solid #e5a900;
color: #ffffff;
font-weight: bold;
cursor: pointer;
text-shadow: 0px 1px 0px #13506D;
width: 100%;
border-radius: 5px;
}
.submit:hover
{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
Conclusion: This was all about, contact form validation in PHP. Hope you like it, keep reading our other blogs posts and do provide us your valuable feedback.
20 Replies to “PHP Contact Form with Validation”
it showing error in validation.php . Undefined variable: data . please help me……
i want to solution for error undefined function test_input() in C:xampphtdocscontact formvalidation.php on line 17&
Hello,
Just wanted to share my findings. To solve the “Undefined variable: data” problem you have to get the function out of the line comment area. In other words simple put your cursor in front of the word “function” and click “enter” on your keyboard :). I however need a bit of help with the email not getting to my email box. I am working on a mac (os 10.9.2) and although this script is operates successfully (THANK YOU GREATLY BTW) if anyone has found or knows of a way to get the php mail function on a local server please share.
Thank you ,
Snow
HI the full function is as follows:-
function test_input($data){
$data = trim($data);
$data =stripslashes($data);
$data =htmlspecialchars($data);
return $data;
}
Fatal error: Call to undefined function test_input() in C:\xampp\htdocs\contact form\validation.php on line 17
i have an error tell me answer
Fatal error: Call to undefined function test_input() in C:\xampp\htdocs\contact form\validation.php on line 17
i have an error tell me answer
I have downloaded script and tried using free hosting website but it does not send the mail which i have submitted. It only shows the message that “Message sent successfully”.
I have changed the the given mail id (“[email protected]”) with my own mail id.
Plz help me sir..
Thanks
I’ve the same problem!!
And the function for filtering input values is writtten in the correct way!
Does anyone knows what goes wrong?
Thats Ok I figured it out
// Function for filtering input values. function test_input($data)
Should be
// Function for filtering input values.
function test_input($data)
it was subimt showed send mail to sucessfully to recived but i was seen in my mail it did not to be came to may email.
so plz help to me
please, I need the download script.
Thanks alot
i try this code but it was an Undefined index: name in C:wampwwwMacam Furniture Websiteinsert.php on line 14
undefined function test_input() in C:\xampp\htdocs\contact form\validation.php on line 17
I Used the above code on my website. When I click submit the page shows blank. No error nothing. Even the mail not received.
Howdy! Great scripts, but after I send the form I receive the info from the form just fine. But if I refresh the browser the form sends again! Even with nothing visible in the form fields!
What’s up with this?? 🙂
Hello!Thanks.Is it possible to publish PHP7 articles on your website .
Hi, Thank yo for the code. I am validating my form using your code. But I was stuck for sometime because of a small problem in the validation.php code. The name of the function test_Input() went to the commented portion, so the code was not finding the function. So please correct the code.
} // Function for filtering input values.function test_input($data)
{
$data = trim($data);
$data =stripslashes($data);
$data =htmlspecialchars($data);
return $data;
}
Thanks & Regards
Sandhya Ashok
Hello,
I want to use this for my website but when the “user” gets the confirmation email it comes from the hosting mail. What can I do that this show to be send from for example “[email protected]”?
Thank you very much
Hello,
I have a question that how to add dropdown list validation in above code.
Thanks,
Yousuf
Fatal error: Call to undefined function test_input() in C:\xampp\htdocs\contact form\validation.php on line 17
i have an error tell me answer