Create A Contact Form in PHP Source Code
Create A Contact Form in PHP Source Code
Source Code
--------------------------------------------------
Have a look at the contact form in the live demo to understand how it works and looks.
For this tutorial you will only need to create just one file. We will call it index.php .
Now that you have created the file, we are ready to code it. First, we will add the HTML Form to
it:
For this tutorial you will only need to create just one file. We will call it index.php .
Now that you have created the file, we are ready to code it. First, we will add the HTML Form to
it:
The above form will post back the data to our index.php file which is the main file for our
contact form. It will use the POST method. The form contains 4 fields namely Name, Subject,
Email and Message. I have also added a hidden input field named Flag which we will use to
check if the user has submitted the form.
Now, you will need to add the following PHP code at the beginning of the index.php file:
Part 2
if( isset( $_POST['Name'] ) && !empty( $_POST['Name'] ) && preg_match( '/[A-Za-z\s]
+/', $_POST['Name'] ) )
{
// The User Has Entered A Name. And The Name Contains Only Alphabets And
Spaces
$name = $_POST['Name'];
}
elseif( !isset( $_POST['Name'] ) || empty( $_POST['Name'] ) )
{
// The Name Input Field Is Empty
$err_msg = "Please Enter A Name";
}
elseif( !preg_match( '/[A-Za-z\s]+/', $_POST['Name'] ) )
{
$err_msg = "Name Can Only Contain Letters And Spaces";
}
if( isset( $_POST['Subject'] ) && !empty( $_POST['Subject'] ) && preg_match( '/[AZa-z0-9\s]+/', $_POST['Subject'] ) )
{
// The User Has Entered A Valid Subject.
$subject = "From Demo Contact Form: ".$_POST['Subject'];
}
elseif( !isset( $_POST['Subject'] ) || empty( $_POST['Subject'] ) )
{
// The Subject Input Field Is Empty
$err_msg = "Please Enter A Subject";
}
elseif( !preg_match( '/[A-Za-z0-9\s]+/', $_POST['Subject'] ) )
{
$err_msg = "Subject Can Only Contain Letters, numbers And Spaces";
}
if( isset( $_POST['Email'] ) && !empty( $_POST['Email'] ) && preg_match( '/[a-zAZ0-9_\.]+@[a-zA-Z0-9]+.[a-zA-Z]+/', $_POST['Email'] ) )
{
// The User Has Entered A Valid Email.
$email = $_POST['Email'];
}
elseif( !isset( $_POST['Email'] ) || empty( $_POST['Email'] ) )
{
// The Email Input Field Is Empty
$err_msg = "Please Enter A Email";
}
elseif( !preg_match( '/[a-zA-Z0-9_\.]+@[a-zA-Z0-9]+.[a-zA-Z]+/',
$_POST['Email'] ) )
{
$err_msg = "Please Enter A Valid Email";
}
Part 3:
<?php
if($err_msg != "")
echo "<div id='ErrorMessage'>$err_msg</div>";
?>
The above code will check if the $err_msg is empty or not. If it isnt empty then it will output
the error to the user.