PHP is a great scripting language that allows many dynamic functions in your site. You can create custom forms, form validation, and email responses using PHP. This article will explain the basics in creating an email form that validates the inputs, produces errors when inputs are typed incorrectly, and send an email to you when submitted.

This section of the code will validate the form inputs

Below is the code you will use to validate whether the inputs have valid data or not. This can be customized for different form field validations.

Note! You can paste the entire code directly in the body section of your webpage to get it working.

<?php 
if (isset($_REQUEST['submitted'])) {
// Initialize error array.
$errors = array();
// Check for a proper First name
if (!empty($_REQUEST['firstname'])) {
$firstname = $_REQUEST['firstname'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$firstname)){ $firstname = $_REQUEST['firstname'];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your First Name.';}

// Check for a proper Last name
if (!empty($_REQUEST['lastname'])) {
$lastname = $_REQUEST['lastname'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$lastname)){ $lastname = $_REQUEST['lastname'];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your Last Name.';}

//Check for a valid phone number
if (!empty($_REQUEST['phone'])) {
$phone = $_REQUEST['phone'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$phone)){ $phone = $_REQUEST['phone'];}
else{ $errors[] = 'Your Phone number can only be numbers.';}
} else {$errors[] = 'You forgot to enter your Phone number.';}

if (!empty($_REQUEST['redmapleacer']) || !empty($_REQUEST['chinesepistache']) || !empty($_REQUEST['raywoodash'])) {
$check1 = $_REQUEST['redmapleacer'];
if (empty($check1)){$check1 = 'Unchecked';}else{$check1 = 'Checked';}
$check2 = $_REQUEST['chinesepistache'];
if (empty($check2)){$check2 = 'Unchecked';}else{$check2 = 'Checked';}
$check3 = $_REQUEST['raywoodash'];
if (empty($check3)){$check3 = 'Unchecked';}else{$check3 = 'Checked';}
} else {$errors[] = 'You forgot to enter your Phone number.';}
}
//End of validation

Sends the email if validation passes

The following code is what sends the email. The inputs must pass the previous validation in order for the email to send. You will need to replace the "to" email address with the email address you want to receive the email to.

if (isset($_REQUEST['submitted'])) {
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "your@email.com";
$subject = "Admin - Our Site! Comment from " . $name . "";

$message = "Message from " . $firstname . " " . $lastname . "
Phone: " . $phone . "
Red Maple Acer: " . $check1 ."
Chinese Pistache: " . $check2 ."
Raywood Ash: " . $check3 ."";
mail($to,$subject,$message,$from);
}
}
?>

Error Reporting Code

This code will print any errors that occurs such as an empty input.

<?php 
//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3>The following occurred:</h3><ul>';
// Print each error.
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';}
else{echo '<hr /><h3 align="center">Your mail was sent. Thank you!</h3><hr /><p>Below is the message that you sent.</p>';
echo "Message from " . $firstname . " " . $lastname . " <br />Phone: ".$phone." <br />";
echo "<br />Red Maple Acer: " . $check3 . "";
echo "<br />Chinese Pistache: " . $check2 . "";
echo "<br />Raywood Ash: " . $check3 . "";
}
}
//End of errors array
?>

Prints the contact form

This is the form that will display for the visitor to fill out.

  <h2>Contact us</h2>
<p>Fill out the form below.</p>
<form action="" method="post">
<label>First Name: <br />
<input name="firstname" type="text" value="- Enter First Name -" /><br /></label>
<label>Last Name: <br />
<input name="lastname" type="text" value="- Enter Last Name -" /><br /></label>
<label>Phone Number: <br />
<input name="phone" type="text" value="- Enter Phone Number -" /><br /></label>
<label>Red Maple Acer:
<input name="redmapleacer" type="checkbox" value="Red Maple Acer" /><br /></label>
<label>Chinese Pistache:
<input name="chinesepistache" type="checkbox" value="Chinese Pistache" /><br /></label>
<label>Raywood Ash:
<input name="raywoodash" type="checkbox" value="Raywood Ash" /><br /></label>
<input name="" type="reset" value="Reset Form" /><input name="submitted" type="submit" value="Submit" />
</form>

You can paste the entire code directly in the body section of your webpage to get it working. We have more tutorials with other methods to send email from your website at the following links.

Using phpMailer to Send Mail through PHP

How to set up FormMail

Continued Education in Course 205: Using PHP to create dynamic pages
You are viewing Section 1: How to create a custom PHP contact form with validation
Section 2: Setting up a database to handle form data from a website
Did you find this article helpful?

We value your feedback!

Why was this article not helpful? (Check all that apply)
The article is too difficult or too technical to follow.
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
How did you find this article?
Please tell us how we can improve this article:
Email Address
Name

new! - Enter your name and email address above and we will post your feedback in the comments on this page!

n/a Points
2014-08-16 2:25 am

very nice..just copy and paste  and it works :)

n/a Points
2014-09-10 3:31 am

i am using the above code for sending mail but getting error like this:

The following occurred:

    '; // Print each error. echo '

Your mail could not be sent due to input errors.

';} else{echo '

Your mail was sent. Thank you!

Below is the message that you sent.

'; echo "Message from " . $firstname . " " . $lastname . " Phone: ".$phone." "; echo "Red Maple Acer: " . $check3 . ""; echo "Chinese Pistache: " . $check2 . ""; echo "Raywood Ash: " . $check3 . ""; } } //End of errors array ?>

 

i don't know why this error come when we click on submit button..pls help me soon..

Staff
19,412 Points
2014-09-10 7:35 am
Hello Anandita,

Be sure to check your code for syntax errors, particularly the placement of the quotes. Did you cut and paste it as is? It seems to work fine for me when doing that. Did you make any changes?

Kindest Regards,
Scott M
n/a Points
2014-09-15 3:24 am

Hi.. Ive problem for make a contact us page. im using such your web for 'post a comment'. its work and nothing error with that. but the comment cannot sent to the email. email cannot received the comment for page contact us. can help me to solve it?

Thanks.

Mira

Staff
19,412 Points
2014-09-15 8:58 am
Hello Mira,

If you are using just this article, then the email should send through fine. Are you one of our customers? Are you using additional SMTP settings to send your email through the server? If so, they will need to be correct in order to send out.

Kindest Regards,
Scott M
n/a Points
2014-09-16 7:13 am

Hi,

I am using this entire code but the only problem is that the form is being emailed on refreshing/reloading the page

Staff
19,412 Points
2014-09-16 10:16 am
Hello Sak,

Thank you for pointing that out. I found the error and corrected it. It has been tested and will not send an email if it is refreshed before the Submit button is pressed. A more updated version of this article should come out soon with a bit more polish.

Kindest Regards,
Scott M
n/a Points
2014-09-18 4:13 am

hi

i will have to write this whole code in page or two page because it has three partition and php code is starting in partition one and ending in partition 2.

Staff
19,412 Points
2014-09-18 9:30 am
Hello Ravi,

You can put all three partitions in the same file. It was only split up on the article to show what purpose each partition serves.

Kindest Regards,
Scott M
n/a Points
2014-09-28 3:37 pm

What if you used radio buttons instead of checkboxes. How would the code look?

I get the html part but the radio validation not sending the value of radio button clicked.

Thanks

Staff
19,412 Points
2014-09-29 9:14 am
Hello Betty,

The checkbox is for when someone may select one or more of the options. Radio buttons force only one selection. Did you have code you wanted us to look at for errors? Replacing the checkboxes with radio buttons needs code modification not only on the form itself, but up where the validation is done.

Kindest Regards,
Scott M
n/a Points
2014-10-17 7:35 am

hello... can i create a home page using php, if yes then can i please get the know how

thanks

Staff
9,036 Points
2014-10-17 9:02 am
If you are not familiar with PHP, you may want to review some of the PHP articles on W3Schools which will teach you the basics of PHP to get you started.
n/a Points
2014-10-20 4:57 pm

This article is very interesting. Thanks!

I "inherited" the maintenance of some websites that use similar PHP functions for the contact forms, so this helps me understand what is going on. 

BUT, I'm having a big problem with browser compatibility. Any idea what I should check on?  This is driving me nuts!

Staff
19,412 Points
2014-10-20 5:04 pm
Hello Lou,

Since the php runs off the server, the functionality should not be affected. The browser incompatibility will likely come in display inconsistencies. These are normally found in the CSS files/statements in the page.

Kindest Regards,
Scott M

Post a Comment

Name:
Email Address:
Phone Number:
Comment:
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

15 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!