Before we begin, it is probably best to start with a disclaimer:
The contact form that we will create here validates user input and minimizes the chance that it could be used improperly, such as for spam. Unfortunately, just about anything on the web can be ‘hacked’ by enterprising hackers. However, this form should thwart most attempts. (See below for more details regarding our release of this code sample, and additional ways to make it hacker proof.)
Alright, ready? Let’s begin. (Want to skip the tutorial? Download all files now.)
A contact form is composed of two main pieces, the HTML which displays the form and the backend code which processes the form. In the code sample below, we’ve provided the HTML which would create a contact form containing a text area and two fields, one for an email address and the other for a name.
<form method="post" action="contact.php">
<input type="text" name="name">
<input type="text" name="email">
<textarea name="message"></textarea>
<input type="submit" name="submit" value="submit">
</form>
The code that processes this form will be a bit more complicated. After all, it needs to accomplish a few things such as:
We will handle each of the above items in turn. Let’s start with with the first item on the list: handling user input.
To handle user input, you need to be able to (1) determine if the form was submitted, and (2) retrieve submitted values. Take a look at the code sample below:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
}
?>
In this code sample, we check to see if the form was submitted by checking the value of the variable $_POST['submit']. Then, within the if statement, we retrieve the other form inputs and save them to the variables $name, $email, and $message.
Well, that was easy enough. Now we have to write code to ensure that users fill in all fields.
To make sure that users have entered all required information, you can test each variable as show in the code sample below:
<?php
$error = "";
if(trim($name)=="" || trim($email)=="" || trim($message)=="")
{
$error = "Oops! All fields are required."
}
?>
In this sample, we have used the PHP trim() function which removes all whitespace. Then we test to see whether or not each variable has a value. If not, the $error variable is set to the error message.
Now onto validating user email addresses. Click below to go to the next page.
Tags: email, PHP
Trackback URL for this entry:
http://www.velvetblues.com/web-development-blog/how-to-write-a-php-contact-form/trackback/
Contact us today for a quote. Click here to submit details regarding your project.
If you are making a general inquiry, send an email to info@velvetblues.com
One user asked about adding a drop down box (or select element) to the form. This could be easily done by adding a new element or replacing an existing element with the following sample code:
<select name="gender"><option>female</option>
<option>male</option>
</select>
Then simply modify the$POST variables at the top of the form, as well as the email message to include this variable.
Be sure to edit the select options and name to something suitable for your form.
Thanks for the code, but how exactly should the other modifications be done? Can you be a little more specific? How do you ad the choics that will drop down?
@Carl, you will need to go through 3 steps:
1. Add that select element to the form HTML code. (ie. the HTML code that we’ve shown under the first subheading)
2. Update the $POST variable. (See section 1: Handling User Input). Assuming that you had a select element like the sample above, with the name ‘gender’, your added code might look something like this:
$gender = $_POST['gender'];3. Update the email message. As you will see, we used a single variable for the ‘message’. So we’ll need to combine the variables for your additional element to include that in the message. So you will need to add another line of code after the $gender and $message lines. The code might look something like:
$message = $gender."\n".$message;I have all that working, last question, and thanks for your help…..
In the e-mail I receive from the form the data entered and selected by the user are included, but not the names of the fields they filled out. Example:
Carl Martin
carl@martin.com
Test
This is a test.
SHOULD BE
Name: Carl Martin
E-mail: carl@martin.com
Subject: Test
Message: This is a test.
To fix this, you’d just edit the variable. Using the example that I included in my last reply, you could achieve the following output:
Gender: Male
Message: Some message
using this code:
$message = " Gender: ".$gender."\n Message: ".$message;or, simpler:
$message = " Gender: $gender \n Message: $message";You have been a big help, all of these issues are now fixed. I am having an issue though. You spoke of another way to have the form send the email and I may need you to elaborate on that. I use Yahoo! for my hosting. For some reason, if I use my e-mail address as the address in the form then the mail is sent to me, if I use any other email address…NOTHING!
Yahoo is one of those restrictive web hosts. You will need to consult their documentation, but I am almost positive that you have to (1) use an email address which is set up via Yahoo for your domain, and (2) set it up under the special email ‘PHP Mail Setup’ options, as a valid address from which mail can be ’sent’…
I haven’t done too much work on Yahoo hosting, so I probably can’t be of any additional help in this regard.
Good luck!
Thanks, I will consult their documentation and their people. I am using the email thats registered and I have done the PHP setup, its just not working, I thought maybe you knew of a workaround. Thanks.
I truly appreciate this script and I have solved the Yahoo! Server issue. I have detailed this below.
In order to get this script to work 100% perfectly with Yahoo! Servers you need to change only a single line of code. This is the original line you need to modify:
$headers = “From: $name \n”;
The modified version should be as follows:
$headers = “From: \r\n”;
The E-mail you actually receive will appear as being sent from Your Email address. To make this something else, Modify the code in this manner:
$headers = “From: FROM NAME \r\n”;
Thanks.
This is not showing up correctly in my post, email me and I will give you the correct data and you can add it, webmaster, thanks.
i sent you an email with the proper code
Thanks Carl, I have added the proper code to the end of the article.
Do you have any code samples lying around for a “Tell A Friend” script that behaves in the same manner as your contact form script?
Hi Carl, no I don’t have a “Tell A Friend” script that I can release. But there are likely tons of them floating around the internet. Google “tell a friend php script“, and you should retrieve some websites which have free samples available.
I did that, most of them do not work property, are cumbersome, or lack features. I love the contact form script and how it works in its own space, no extra windows, etc. Any idea what would have to be modified to make it send data like a refer a friend script? thanks.
Depending on what features you’d want, it will most likely be a bit more complex than this script.
But the simplest possible implementation would be one where you just change the recipient email address and have it point to a user-supplied email address for their friend. And then you could have a standard message that is sent to all ‘friends’…