Contact forms play an integral part in websites today. Nearly all websites need a contact form to allow your users to get in touch. Unfortunately contact forms, in my opinion, are not as simple as perhaps they should be, and for beginners setting up a contact form can be very daunting. In this 3 part series, I’ll show you first how to process data from a form using PHP and email it to a specific address. In Part 2 we will look at how we can effectively style our form to make it easier for the users, and in the final part we will jazz our form up using jQuery and Ajax. All you need is a basic knowledge of HTML and CSS, so lets get going!
Basic HTML Structure
For the purpose of this tutorial we will be keeping it simple, with just 4 fields: “Name”, “Email”, “Why are you Contacting?” and “Your Comment”. This is a pretty regular structure for a basic form. So create a new PHP file and lets get going! The HTML mark up looks like this:
<form action="process.php" method="post"> <p><label for="name">Name</label> <input name="name" type="text" /></p> <p><label for="email">Email</label> <input name="email" type="text" /></p> <p><label for="why">Why are you Contacting Us?</label> <select name="why"> <option value="I want a website">I want a website</option> <option value="I found a bug">I found a bug</option> <option value="Other reason">Other Reason than above</option> </select></p> <p><label for="comment">Comment</label><textarea name="comment"></textarea></p> <p><input name="submit" type="submit" value="Send us a Message!" /></p> </form>
There are a few things that need explaining here. Firstly, the two form attributes, “action” and “method”. The first is which page we want to load when the user clicks the submit button, and the second is the method that will be used for sending our data to that page. We will be including our PHP code in the same page, so by leaving the “action” attribute blank, we tell the form to reload the same page. There are two types, “get” and “post”. Don’t worry, we will discuss these two in the next section. Next up we include each field in a paragraph tag and use the label element to show which field the text is denoting. Please note that the “for” attribute of the label must be the same as the “name” attribute of the corresponding input tag. Each input is given a name, this is how we will refer to it in the PHP code later on. The only other slightly odd thing is the mechanism that the select tag takes. The select element will provide a drop down of options, all of which are stored in the option tags that reside inside the select tags. We don’t need to give each option a name, but we do need to give them a value so we know which one the user has selected. Note that we do give the select tag a name, so we can refer to that in our code. But more on that later.
Get & Post
As I mentioned earlier, there are two methods for getting form data from our page to our code to process it. They work different ways and as such your situation will usually dictate which one you choose.
Get
The “get” method posts each value in the URL. This is used by google when searching. For example, if I search on Google for “The Web Squeeze”, the URL returned looks something like this:
http://www.google.co.uk/search?q=The+Web+Squeeze
Google takes the value I entered into the search field (which is essentially a form like ours) and appends it to the URL, assigning what I typed to the value of “q”. If we were to use “get” on our form, it would look something like this:
www.yoursite.com/process.php?name=Jack&email=demo@jack.com&why=I+found+a+bug&comment=there+is+a+bug
This does not seem very practical. For one, if the user enters a long comment, the URL is going to be absolutely massive. Also, Google uses the “get” method so I can save a certain search if I wish to return to it at a later date. There is little chance of our users deciding to submit the same data again, so Get does not seem the right choice for us. As another tip, because the data is sent as text in the URL, passwords could easily be exposed, so if you are asking the user for sensitive data (email addresses also could be seen as sensitive) don’t use Get.
Post
The “post” method does not append data to the URL but is sent in the body of the request after the headers. This might all seem very complex, but the gist of it is that data sent via Post is never shown on the computer screen to the user, so any sensitive data is much better sent via Post.
Best for Us
As we potentially could have users entering a lot of data, and we are asking for some sensitive data in the form of email addresses, we are going to use the post method.
Lets get processing
Add your opening and closing PHP tags to the very top of your page. And by very top, I mean before the doctype.
The first thing we need to do before processing is to check if the form has actually been submitted. If you check your HTML, you will notice that the Submit button actually has a name attribute, which I gave the value of “submit”. If the form is clicked, then the value “submit” will have been sent via the post array, so we can check if it exists.
Hang on, Post array?
When the data is sent, it is sent in the form of an array. An array is essentially a big list of data. When we use the post method, we can get the data from our post array. We access the data like so:
$_POST['fieldname']
$_POST shows that we are accessing data from the post array. And then we need to add our field name. So if I wanted to find out the value of the name field, I would do so like so:
$_POST['name']
So, to see if the submit button has been clicked, we need to know if $_POST['submit'] exists. We can do this using a PHP function called isset() to check if it is set. This function either returns true or false depending on whether the item exists.
So we are saying “if there is an item in the POST array with a name of “submit” then our form must have been submitted.” If our form is not submitted, this if statement will evaluate to false. So, now we have our check, we can actually get on to processing it.
Are any fields empty?
Firstly we need to check if the user has filled in all the fields. We know that the “Why” field will be filled in because we only gave them two choices, so they have to select one. For all the other fields which are text fields we just need to check if they are empty. We can do this like so:
if($_POST['name'] == "") { //the name field is empty }
Now we know if it’s empty, we need to store this error so we can later tell the user. Because there potentially may be more than one error, we may end up with a list of errors, so we can create an array to store them in. Update your process.php so it looks like this:
if(isset($_POST['submit'])) { //create an empty errors array $errors = array(); //our form has been submitted if($_POST['name'] == "") { //the name field is empty $errors[] = "The name field is empty"; } }
First we create a blank array and name it $errors. Because we didn’t put anything between the brackets, we create a blank array. We then check if our Name field is blank – note the use of double equals signs – in PHP a single equal sign assigns the value, and two of them next to each other equates them. So if our field is empty, we then add an item to our $errors array, by typing $errors[]. The empty square brackets tell PHP to add a new item to our array. We then continue in this manner for all of our fields, until process.php looks something like this:
if(isset($_POST['submit'])) { //create an empty errors array $errors = new Array(); //our form has been submitted if($_POST['name'] == "") { //the name field is empty $errors[] = "The name field is empty"; } if($_POST['email'] == "") { //the email field is empty $errors[] = "The email field is empty"; } if($_POST['comment'] == "") { //the comment field is empty $errors[] = "The comment field is empty"; } }
More Advanced Checks
Now we have done that there are only a couple more things we can do. Firstly, we can do a bit more of a check to see if the email address is actually an email address. There are very complicated ways to do this, mainly using Regular Expressions, but we will use a much more simple method (all be it less secure) to test ours, and just see if there is a “@” sign in the field. We can do this using the stripos() function. It takes these arguments:
stripos(string to search, what to search for)
This will return true or false depending on if it is found. So we can now perform the following if statement:
if(!stripos($_POST['email'], '@')) { $errors[] = "The email address was not valid"; }
Please note the exclamation mark infront of the stripos() function. This means “if not” – so if stripos() evaluates to false (a @ was not found) then we add another item to our errors array.
What About Spammers?
Now we have our form and basic checks left, there is one thing left to do. Add another field to our form, just above the submit button:
<p><label for="spam">What is 2 + 2?</label><input type="text" name="spam" /></p>
And then add another if statement to our checks:
if($_POST['spam'] != 4) { $errors[] = "The Spam question was answered incorrectly"; }
What we do here is see if the spam field is not equal to four. If it isn’t then we add another item to our errors array.
Can we Send Email?
We have now finished our checks. Congrats, you are on your way to sending your first form. We now need to see if we have any errors. If we have, then we cannot send the form yet, as we need the user to correct their errors. If we have no errors, then we are free to send the form.
if(count($errors) == 0) { //no errors, we can send the form } //if there are errors, we need to do some more work
The count() function in PHP counts how many items there are in the array. If there are none, that means we have not found a single error and can continue on. If there is one or more, then we need to get the user to sort it. Let’s concentrate on getting the user to fix their problems first.
You did it Wrong!
Now, we know that they have done it wrong. Something went wrong, maybe there was a typo that was wrong, who knows. We need to display the errors, somewhere that the user can see them. Just before the
Hi there and thanks for the article, some generally good tips here. I did notice a few things though.
These empty checks:
if($_POST['name'] == "") {
//the name field is empty
$errors[] = "The name field is empty";
}
Should be re-written as some spaces will get around them. PHP has an empty function, combined with trim it is effective:
if(empty(trim($_POST['name']))){
//Name is empty
}
You can do much better and thorough email validation without regular expressions if you’re using php5 (which everyone should be). As it is right now, your open to spam as spammers could enter multiple valid email addresses. Try using filter_var:
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
//email is not valid, set error.
}
Lastly, you need to sanitize all of your user data before sending the email. This is a must. I’m talking about these lines:
$name = $_POST['name'];
$email = $_POST['email'];
$why = $_POST['why'];
$comment = $_POST['comment'];
Thanks for taking the time to write this article Jack
Hi Drew,
Great comment, thanks very much.
I was unaware of the FILTER_VAR function in PHP 5, so thanks for that, it looks fantastic
As for sanitizing data that’s a very good point.
Thanks for taking the time to write that comment, it’s very useful indeed.
Regards,
Jack.
I am having trouble getting the “you did it wrong” section to function. When using the suggested code:
Name<input type="text" name="name" value="”>
the php code shows up in the text boxes. Am I missing something?
Hi Aline,
Shortly I will get a demo uploaded for you to download and compare against your code. Be sure to save your page as .php and not .html, you have done that I presume?
Line 55 under the “Full Code” heading reads
Its been a while sense I’ve done any real code editing, but this doesn’t seem right.
@Autistic Geek: All fixed! Terribly sorry about that!
Hi jack,
Thanks for the information.I am trying to leaner the PHP contact form and found this article to be of great use.Could you please let me know the method to check if the PHP contact form is working or not on a local machine without uploading it on the server.Please ingnore if you consider that the question is too dumb.
A copy of your answer to my email id would be highly appreciated
regards
Manik
Hiya, thanks for this. I have a contact form to make this morning and will use this as a base.
I have to agree with Drew, it’s definitely a good idea to sanitize your variables before sending them, I guess this would work:
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$why = filter_var($_POST['why'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
Anyway, I’m going to play around with it now.
Btw, a bit pedantic maybe, but the
for
attribute of alabel
refers to theid
of a form field, not thename
.Thanks!
i keep getting the message “There was a problem with your form. Please email us directly via…..”
Even when I copy the exact code you have written there’s still no sucess, could this be an issue with the server? Emailing is enabled and I have other forms that are able to send emails on the site… the complete code I have is as follows:
print("<?php $file_name = "contact"; ?>
<?php
if(isset($_POST['submit'])) {
//create an empty errors array
$errors = array();
//our form has been submitted
if(!isset($_POST['name']) || strlen(trim($_POST['name']))==0){
//the name field is empty
$errors[] = "You did not enter your name";
}
if($_POST['email'] == "") {
//the email field is empty
$errors[] = "You did not enter an email adress";
}
if(!stripos($_POST['email'], '@')) {
$errors[] = "The email address you entered was not valid";
}
if(!isset($_POST['msg']) || strlen(trim($_POST['msg']))==0){
//the message field is empty
$errors[] = "You did not enter a message";
}
if($_POST['spam'] != 4) {
$errors[] = "You didn't answer the anti-spam question correctly";
}
if(count($errors) == 0) {
$to = "name@domain.com";
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
$message = <<<DATA
Name: $name
Email: $email
Subject: $subject
Message: $msg
DATA;
if(mail($to, $subject, $msg, $headers) {
$success = true;
} else {
$success = false;
}
} else {
$success = false;
}
}
?>
Ways to get in touch
For any enquiries you have complete the form to email us, you may also use other “ways to get in touch” to reach us. For a quote please complete the form located here.
Ways to get in touch
Email:
Telephone:
Postal Address:
There was a problem with your form. Please email us directly via
01274 123456
12 Abcde Street
Bradford
West Yorkshire
BD1 2EF
Contact us
<?php
if(isset($_POST['submit'])) {
if($success == true && count($errors) == 0) {
echo "Thank you, your form has been submitted!”;
}
if(count($errors) == 0 && $success == false && isset($_POST['submit'])) {
echo ‘There was a problem with your form. Please email us directly via name@domain.com.’;
}
if($success == false && count($errors) > 0 && isset($_POST['submit'])) {
echo “”;
foreach($errors as $e) {
echo “$e”;
}
echo “”;
}
}
?>
Name:
Email:
Subject:
Message:
What is 2 + 2?
(Anti-spam question)
“);
hi jack
i to have tried to add email headers the mail fucntion
and i am getting the something wrong with form error all the time. all i wish to do is add email headers as the form doesnt have reply to email and from etc. also it isnt html rendered. the tags show.
any ideas i would really appreciate explaination of the if(mail()) {} fuction i get what it is doing but i dont see what its condition is?
many thanks
darren
Thanks for such an easy to follow tutorial! I’m fairly new to PHP and especially forms, so found this post and the corresponding comments very helpful.
I’m the developer of a PHP contact form creation class called Contacular. Head to http://contacular.co.uk/ to take a look if you wish!
Can someone please help me find the errors in my code I have tried everything and can not seem to get the code to work thanks.
<?php
if(isset($_POST['submit'])) {
//create an empty errors array
$errors = array();
//our form has been submitted
if($_POST['name'] == "") {
//the name field is empty
$errors[] = "The name field is empty";
}
if($_POST['date of birth'] == "") {
//the Date of Birth field is empty
$errors[] = "The date of birth field is empty";
}
if($_POST['email'] == "") {
//the email field is empty
$errors[] = "The email field is empty";
}
if($_POST['copy and paste your work here'] == "") {
//the copy and paste your work here field is empty
$errors[] = "The copy and paste your work here field is empty";
}
if($_POST['comment'] == "") {
//the comment field is empty
$errors[] = "The comment field is empty";
}
if(!stripos($_POST['email'], '@')) {
$errors[] = "The email address was not valid";
}
if($_POST['spam'] != 42) {
$errors[] = "The Spam question was answered incorrectly";
}
if(count($errors) == 0) {
$sendto = "vernonstallins@yahoo.com";
$title = "Submit your work";
$name = $_POST['name'];
$dateofbirth = $_POST['date of birth'];
$email = $_POST['email'];
$paste your work in the text box below = $_POST['copy and paste your work in the text box below'];
$choice = $_POST['choice'];
$comment = $_POST['comment'];
$message = <<<DATA
Name: $name
date of birth: $date of birth
Email: $email
Paste your work in the text box below: $Paste your work in the text box below
Choice: $choice
Comment: $comment
DATA;
if(mail($sendto, $title, $message)) {
$success = true;
}
}else {
$success = false;
}
else {
$success = false;
}
}
?>
Submit your work
.style1 {
font-family: “Times New Roman”, Times, serif;
font-size: medium;
}
.style2 {
font-family: “Times New Roman”, Times, serif;
font-size: medium;
margin-left: 40px;
}
.style3 {
margin-left: 40px;
}
.style5 {
font-family: “Times New Roman”, Times, serif;
font-size: x-large;
}
Submit one of your works to be posted on
Day Dream Reading!
If your worked is deemed to contain plagiarized and/or offensive material then it will not be posted.
Name
Date of Birth
Email
What kind of work would you like to submit?
<option >poem
<option >story
<option
>essay<option >other
Paste your work in the text box below.
In your comment please specify what contact info you would like added to your works, if any.
Such as Telephone number, e-mail, etc. Thanks.
Comment
Please answer the below question to prove you are not a computer. Thanks.
What is 6 x 7?
If you are having issues getting something to work using the above tutorial, you should check out our support forum for web design and development.
http://www.thewebsqueeze.com/forum/
This is is a wonderful tutorial, including the follow-up comments. It is very simple to follow yet highlights some important aspects of PHP. Finally I understand the difference between GET and POST due to the way you have explained it.
Regards.
Hi Jack,
Thanks for this write-up, it is a good base. I took into account the suggestions of the above commenters, and changed a few things to match my taste.
http://www.uncharteddesign.com/blog/2010/05/server-side-php-contact-form-with-validation/
Email validation
Invisible spam protection
Better empty checks
Sanitizing of values submitted
No jquery, substituted some better php errors
Email headers to correct the from address and name
No html message
If you have any concerns about my crediting of you or reposting this, please do let me know.
Jordan