Posted on: Wednesday, June 6th, 2007
Ok so you want to build a simple form that takes basic contact information from your clients and sends it to a given email address (or addresses), so where do you start? Well you have taken the first step by reading this tutorial.
I am writing this tutorial in response to the amount of forum postings I have seen on the matter recently so here we go
Step one:The form.
The form we are building will be very basic, it will gather the information, validate the email address then send a formatted plain text email to the specified email address.
The fields I will be collecting from the page are: Name, email and comments. These are the staple requirement of most pages on the net.
We start off our page by putting our usual DOCTYPE information:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP Form Example</title>
</head>
<body>
Now we start our contact page, with our header and open the form control:
<h1>Contact Us </h1>
<form action="<?php $SERVER['PHP_SELF']; ?>" method="post" name="contact_us" id="contact_us">
Next we add out form fields remembering to give each one a label, if you remember we are using just 3 fields here, name, email and comment.
We then add the ‘Submit’ button and close the form.
<p>
<label for="name">Name</label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="comment">Comment</label>
<textarea name="comment" id="comment"></textarea>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
Note: I always add the paragraph tags around the form controls as it makes them easier to style with css.
And thats it for the form so now we close the page:
</body>
</html>
Step 2: The PHP
Now we will create some simple PHP that will check the email address to see whether it is valid, then if it is send the comments, if not then return an error
We always start by opening PHP with its FULL tag
<?php ?>
Then within these tags we add our code.
First we check that the user has clicked the ‘Submit’ button
if(isset($_POST['Submit'])) {
Then we define are variables for use in the sending later on
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
Now we can define where we want the email to be sent to and what the Subject of the email should be
$sendto = "example@email.com"; //enter your email address here
$subject = "A new comment has arrived via your site";
Next we build the body of our email
$body = 'A new comment has arrived via your website from: '.$name.' ('.$email.')
Name: '.$name.'
Email: '.$email.'
Comment
---------------------------------------'.
$comment;
Now we have all of the building blocks of our PHP mail() command, we could simply slot them in to place as shown below, but we also want some email address validation.
mail($sendto, $subject, $body, "From:".$email);
So first we have to add our php email address validator, (download it here and upload it to the same directory as the contact us page (right click and save as). REMEMBER TO CHANGE THE FILE TYPE TO .php!)
First we incude the file, then we check our email address. If the email address is valid we send the mail, if not an error is returned
include("emailvalidator.php");
if (check_email_address($email)) {
mail($sendto, $subject, $body, "From:".$email);
echo "Mail sent successfully!";
} else {
echo "The email address you supplied in invalid please try again";
}
We then close the ‘if’ statement from the submit button and close our php tag
}
?>
So now the full code you should have is:
<?php
if(isset($_POST['Submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$sendto = "example@email.com"; //enter your email address here
$subject = "A new comment has arrived via your site";
$body = 'A new comment has arrived via your website from: '.$name.' ('.$email.')n
Name: '.$name.'n
Email: '.$email.'n
Commentn---------------------------------------n'.
$comment;
include("emailvalidator.php");
if (check_email_address($email)) {
mail($sendto, $subject, $body, "From:".$email);
echo "Mail sent successfully!";
} else {
echo "The email address you supplied in invalid please try again";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<h1>Contact Us </h1>
<form action="<?php $SERVER['PHP_SELF']; ?>" method="post" name="contact_us" id="contact_us">
<p>
<label for="name">Name</label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="comment">Comment</label>
<textarea name="comment" id="comment"></textarea>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
You should now have a fully functioning form ready for styling with CSS (further tutorial to follow). If you have any problems simply leave a comment below and I will reply as soon as possible.
Remember: Change the $sendto variable to your email address!
EDIT
You also need to create a page called sucess.php and upload it to the same directory as your contact us page. The script automatically re-directs to the new page after completing.
The page should say something like ‘Thank you for submitting your comment, we will be in touch sooner than you think. Please continue to browse our site.
Popularity: 100% [?]
archives
PHP, 
pages
categories
Hi..Thanks for this form. But it seems that the emailvalidator.php file is empty. It shows 0KB after downloading it.
Hi, sorry you are having problems, I have now changed the file to a .txt file. Download it as stated above and change the filename to .php.
Dan
Hello Daniel,
The code seems to be working perfectly. But the problem that I am getting is that after submitting the form, I don’t get any mail. I have tried putting all my email ids in the code, and i have tried sending like 4-5 mails, but none received yet. The only change that I did was that, I did not insert the PHP code in the contact page. I inserted in a new page named thanks.php. Hope I am clear in explaining my problem.
Hello Daniel,
You were absolutely right. It sure is the problem of the special header that is “FROM:” inside the mail(). I removed that completely, and it works perfectly now. I do get a mail but with the “Nobody” in the from field in my email program.
THANK YOU SO MUCH. THIS CODE ROCKS!!!
Hi,
The problem can be solved by inserting the following simple line:
mail($sendto, $subject, $body, “FROM: “);
Thank you Daniel. This code is really good.
Hi.
Good design, who make it?
I made it, why do you ask?
Dan
Firefox can’t find the file at /C:/Documents and Settings/Werther/Desktop/.
what happ ? my file` is not uploaded - this is the problem ?
Yes this will be the problem. You need to have the files hosted on a server that supports PHP.
You are a god!
I’ve looked everywhere for just a step-by-step code to tell me what to do. All except this confuse the hell out of me. Top Marks!
Great tutorial - just what I needed; thank you. However, I’ve got 2 queries:
1) instead of your echo statements in the example script, how can I redirect to my own “thank you” page and “error” page?
2) how do I POST input from tickboxes?
Probash, the code you want is
header("Location:sucess.php");to replace the echo statement and also under the else, change to error.php.
How can I style the message that I get into my email. Is pretty messy and is coming with that “/n” from the code. Thanks
To style the email you would need to maybe use HTML email. This is a completely different tutorial which i intend to produce soon.
However, the reason that the email is so unformatted is that it is only for admin to see, ie. the person who replies to queries.
To get rid of the /n simply delete it and add a line break (press enter) in your code, this should format the line endings correctly.
Thanks, Dan
Than you for this easy to understand tutorial. Is there any way to make the fields remember what the visitor typed if he put any invalid email address and is redirected to error page?
There is by using sessions in PHP but this is another extensive tutorial and not something I can cover in a comment.
If you wish me to produce some code for you I would have to charge.
Dan
And do you have any hourly rate?
My hourly rate is £25 or $50, let me know if you require any assistance…
Thanks, but I managed to make it myself. Any idea I don’t get emails from gmail accounts? Is it has something to do with email_validator? Thanks
It shouldnt have anything to do with the email validator as the all it looks for is an email address with at least 4 parts (1)name (2)@ (3)domain. (4) TLD ie com, co.uk
So anyone@gmail.com passes this test.
Have you checked your junk mailbox? As alot of free web serves seem to get junked…
Dan
I rechecked that many times and I found that yahoo doesn’t get the mails from google users not even in bulk folder. But I checked again on my google mail account and on there I get everything. I don;t know any possible explanation. Maybe you have a clue. Thanks.
Because I checked too many times on my active yahoo address I decided to try on my other email address. So yes I’ve got the message in there but in spam. Does that have something to do with the form or there is other explanation?
does anyone knows if there is any other information about this subject in other languages?
Not that I know of but you may be able to use Google Translate to translate this page, see this link for more information http://googlesystem.blogspot.com/2008/03/useful-google-translate-addresses.html
Dan Cullinan
Daniel,
Hi, and firstly thanks for taking the time to help those less experienced!
Firstly I’m very inexperienced so please excuse what is probably a simple question, but I’ve been trying to build the “Contact” page into my website and I’m a little confused as to what to do at the
include(”emailvalidator.php”);
step of the code. I’ve downloaded the validiator, saved it as a php file BUT do I just then include this php file in my website directory, or do I open the file and paste it into the brackets?
I’ve tried both options but when i trial the page and submit it I get a “this page cannot be found” error.
Thanks
Alan C
Hi Alan,
you need to download the file provided and then upload it to the SAME directory as the contact form page.
Then simply use the code ‘as is’, no editing of it is needed apart from the custom fields.
You may get some errors whilst testing locally if you dont have a server installed on your pc. Also you need to create the ’success.php’ file with a short thank you, otherwise on completing the form and submitting it will have a 404 error for success.php.
Hope this helps.
Dan
Dan,
Thanks for the reply,I was including the file in the same directory, so that can’t be the reason for the error message. But you’ve confused me with your comment that I need to create a “success.php”" file with a short thank you!
I thought the “full” code above was all I needed -and for the benefit of others where do you mention this, or have I missed it.
Where/how do I insert this extra code - and why not include it in your code in the first place.
If, as you obviously are, trying to help others why not make the code comlpete so it’s just cut and paste. Anything which HAS to be changed could be highlighted by say bold italics in a different colour.
Regards
Alan C
Sorry, I have not mentioned in the tutorial that the code re directs after completion to a new standard page called success.php.
Simply create this page as you would any other page with a short message saying thank you etc, and save it as sucess.php and upload it to the same directory.
All other changes that need to be made are explained in full in the tutorial.
Note the edit at the bottom of tutorial.
Dan
After couple months of using your form on a popular website with good results in google is getting a lot of spam in the last month. There is anything I and the other who are using the provided form to avoid this? Thank you very much.
respelled: “There is anything, I and the other who are using the provided form, can do to avoid this?”