I recommend you read Part I and Part II of this series if you haven’t already.
In the previous posts on this subject, I’ve explained the basic page template and the validation that we need to do for our contact form. Finally we can deal with the actual emailing of the form content and then put it all together.
Emailing the form content
The theory behind this is to grab all of the information from the form, put it into a message variable. Perhaps also add in some extra info for ourselves eg. their IP and browser type. So first off we need to get all of the information from the form. To make lives easier for ourself in the future (and we’ve already got a reasonable bit of strict validation in), we can just run through every form element and add it into the message eg.
$message = ""; foreach ($_POST AS $key => $value) : $message .= $key.": ".$value."\n\n"; endforeach;
This will mean that you can add new fields to the form and not have to worry about adding additional code into the PHP to get those new fields, as this will get every key and value from the $_POST array. Is it the best option? In theory no. All it would take is someone to post the correct fields plus hundreds more, via their own script, to your form processing script, and your email would be very long. But at the same time, it’s only content, and the email is only coming to you. If you found this to start happening then I’d recommend learning how to retrieve individual field values instead. However, for this form we’ll stick with the above as it’s quicker for now!
So, we’ve got the basics of our message created. We want to add some additional info below it so we can use:
$message .= "\n\nSender Info:\n"; $message .= "IP: ".$_SERVER['REMOTE_ADDR']." http://ws.arin.net/whois/?queryinput=".$_SERVER['REMOTE_ADDR']."\n"; $message .= "Browser/OS: ".$_SERVER['HTTP_USER_AGENT'];
This is just a fairly simple addition. The second line will echo out the IP address and link to the whois lookup for it, in case you may want to check where the person is from. Then the final line just tells you the person’s browser and operating system. They’re not 100% accurate, but for most legit people contacting you, it will be, and it’s sometimes interesting to know what people have. Also, if you start to get multiple messages off what appear to be different people, but have the same IP, then you know you could block that IP as they’re clearly just stalking you
Next we need to create our email headers. Whilst a basic header of
"From: ".$email
Will usually work, some servers may reject the email if the headers do not appear complete. So let’s build the headers up properly.
$headers = "From: ".$_POST['cfname']." < ".$_POST['cfemail'].">\n"; $headers .= "Mime-Version: 1.0\n"; $headers .= "Content-Type: text/plain; charset=ISO-8859-1\n"; $headers .= "Content-Transfer-Encoding: 8bit\n"; $headers .= "Return-Path: < ".$_POST['cfemail'].">\n"; $headers .= "Errors-To: ".$to_email;
This code sets the email to be a plain text email. If you wanted to use HTML in the email then you’d change line 3 from text/plain to text/html. The last line uses a variable which we’ll set at the top of the file, just a simple To email address, so that you don’t have to change it everywhere if you want to change your email in the future.
Then finally we have the code to send the email:
mail($to_email, $subject, $message, $headers);
Again, the $subject will be set at the start, so that you don’t have to go poking around the code once it’s all set up.
You’ve then got two options once the email is sent. You can either return a thank you message on the same page, or redirect the user to a thank you page. Personally I opt for the latter and use the code
header("Location:http://".$_SERVER['HTTP_HOST']."/".$redirect);
Where $redirect is the path to the thank you page on your site from the root eg. “contact-form/thank-you/”.
Final Functions
Just to explain a couple of final functions. These are not essential but as they’re in the final template they just need a brief explanation.
// clean up the form content foreach ($_POST AS $key => $value) : if (get_magic_quotes_gpc()) : $value = stripslashes($value); endif; $formstuff[$key] = strip_tags($value); endforeach;
This first function will run through every value submitted in the form and strip and backslashes added by magic quotes (if they’re set to on) and also run strip_tags() which will strip out all HTML tags. Afterall, no one should be sending HTML to you in your contact form
If you want to allow it (considering the email is sent as plain text so the code would just display) then remove line 7.
// function to print out form value, stripping any added backslashes
function get_value ($formvalue) {
if (!empty($_POST[$formvalue])) :
if (get_magic_quotes_gpc()) :
$form_value = stripslashes($_POST[$formvalue]);
endif;
echo $form_value;
endif;
}
This function is used when someone partly completes the form but triggers and error. We want to redisplay their content so that they don’t have to retype it. Again, it just checks if magic quotes are set to on and if they are it strips the backslashes out.
// this is the message if there is one.
if (!empty($error_msg)) :
echo "<ul>\n"; // perhaps style the warning class to a bright colour
echo $error_msg;
echo "</ul>\n";
endif;
Finally the code to echo our our errors that we’ve saved. Again, only used if someone partially completes the form and triggers a validation error. This will display the errors in a list.
Put it all together
Now we can finally put it all together, along with a couple of if statements to check that we can proceed. The final template can be downloaded. It’s well documented so you should be able to run through it all without a problem. You may need to edit the divs and markup around the form to suit your own template, however comparing this to your page.php or index.php file will show you what needs changing.
Leave any questions below and I’ll do my best to help you out. Ideally mention the line number(s) if it’s about the code, that you’re asking about so that I can look it up ![]()












Alex Cristache | September 7th, 2008 at 11:23 am #
Thanks Sarah, this series will come in handy as I really need to better setup my “Contact” page.
dave | September 7th, 2008 at 6:01 pm #
Thank you Sarah,
Fantastic finish to the creating a contact form series, extremely helpful…
dave | September 7th, 2008 at 6:47 pm #
Sarah,
Just a few questions if you don’t mind?
To add multiple recipients for the contact form to be sent to, can I just add them to the $to_email = (line 13)? …just checked & this works fine.
I also want to send the form submitter an email upon submission, any idea how I do this?
I have tried adding:
mail($cfemail, $subject_2, $message_2, $headers);
and
mail($formstuff['cfemail'], $subject_2, $message_2, $headers);
under the original:
mail($to_email, $subject, $message, $headers);
But it doesn’t seem to work, any ideas?
Thanks, again, dave.
Sarah (Post Author) | September 8th, 2008 at 2:11 am #
Alex - you’re welcome.
Dave, the line
mail($formstuff['cfemail'], $subject_2, $message_2, $headers);Should work fine. Although because your headers also contain this email address what you may find is that your server may allow the email to come to you from that address, as your email is registered on the server, however either the server won’t allow a script to send an email off the server to an unrecognised address, or it won’t allow an unrecognised address to send an email to an unrecognised address.
So I would try a second address registered on the server first, see if that works. Then try for the second line to just simply be
mail($formstuff['cfemail'], $subject_2, $message_2, “From: Your Website “);Changing the last parameter to be your site address and a from address associated with your domain. Then try that with an off server address eg. GMail address, and see how that goes.
Otherwise you may be simply restricted to not being able to have forms send emails to off server accounts - this is something you can clarify with your host.
Bogdan Radu | September 8th, 2008 at 4:39 am #
Great article thank you man!
Adidas Trainers | September 8th, 2008 at 6:51 am #
Wow, nice website man
dave | September 8th, 2008 at 8:00 am #
Thanks Sarah,
mail($formstuff['cfemail'], $subject_2, $message_2, “From: Your Website “);
worked a treat.
Rahul Joshi | September 27th, 2008 at 10:20 am #
Hi,
I tried implementing the Contact Form in a wordpress theme, but i keep on getting an error of - Parse error: syntax error, unexpected T_STRING
It comes where i have defined the redirect link and if i comment it then it comes on the line where i have defined the mail subject.
Any idea what might be the reason for this error?
Rahul Joshi | September 27th, 2008 at 10:22 am #
Oops!
Sorry I figured it out.. It was a very silly mistake of unclosed quotes..
Sarah (Post Author) | September 27th, 2008 at 10:43 am #
Glad you sorted it
Rahul Joshi | October 2nd, 2008 at 4:15 am #
Hi,
I created a contact form following the same tutorial, but it isn’t working..
You can check the link- http://www.rjdesignz.com/contact. Also even the validation is not working on the site. I have also uploaded the php template i am using on the contact page here- http://www.rjdesignz.com/contact-upload/contact.zip
Sarah (Post Author) | October 4th, 2008 at 4:42 pm #
Hi Rahul,
I’ve taken a look at the file you’re using and it looks fine to me. The only issue I can think of is that you’re on a Windows server using IIS as opposed to Apache, and possibly your mail() function doesn’t work. You may need to use SMTP instead.
You can check this by creating a quick PHP file and adding the following line of code
<php mail("toyou@gmail.com", "Just a quick test", "Just testing the mail function", "From: you@rjdesignz.com“); ?>Put that in a file and upload it, and run it. Nothing will happen in the browser but check if the email arrives (obviously change the two email addresses).
If that doesn’t work then the only other possible issue is that your server requires the from address to be a registered pop account on the server, to protect from spamming. So make sure that’s the case and see if that works.
If it still doesn’t then you may need to contact your host and ask them if the mail() function should work. If it doesn’t then I recommend trying out the CForms II WordPress plugin which will give you a lot more choice and hopefully you’ll get that working on your site.