469,921 Members | 2,110 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,921 developers. It's quick & easy.

Is this a secure PHP mail form?

Hey folks,

I was going to include a contact form on my website. Well, in the first place that seemed an easy thing to do with a form that prompts a PHP file validating the input vaiables and using it's mail () function to send the mail. However, as I got more into that topic I realized that one should be really concerned about the validation part to prevent spam abuse.

There are shiploads of 'mail scripts' available with each of them has it's pros and cons as widely discussed and even argued in various forums (e.g. an example on thescripts.com: http://www.thescripts.com/forum/thread640302-mail+form.html). With all that controversion about the mailform security issues I thought I'd start a forum thread that may help to understand relevant variable validation in a PHP driven contact mail form.

As an example I like to discuss the 'php from mailer' availabe on www.thedemosite.co.uk. It employs two files, an html file with the form including brief javascript validation for input data and as a second file php driven variable validation to prevent spam abuse through header injection.

The form and javascript validation part looks like this:
<form name="phpformmailer" action="contact.php" align="center" method="post">
<div align="center"><table>
<td>Your name:</td>
<td ><input type="text" size="29" name="name"></td>
<td>* Your email address:</td>
<td ><input type="text" size="29"
<tr align="middle">
<td>* Confirm email address:</td>
<td ><input type="text" size="29" name="email2"></td>
<td >* Subject:</td>
<td ><input type="text" size="29" name="thesubject"></td>
<td >&nbsp;<p>* Your request or query:</td>
<td ><textarea style="FONT-SIZE: 10pt" name="themessage" rows="7" cols="27"></textarea></td>
<td ></td>
<td ><script language="JavaScript"><!--
function validateForm()
var okSoFar=true
with (document.phpformmailer)
var foundAt = email.value.indexOf("@",0)
if (foundAt < 1 && okSoFar)
okSoFar = false
alert ("Please enter a valid email address.")
var e1 = email.value
var e2 = email2.value
if (!(e1==e2) && okSoFar)
okSoFar = false
alert ("Email addresses you entered do not match. Please re-enter.")
if (thesubject.value=="" && okSoFar)
alert("Please enter the subject.")
if (themessage.value=="" && okSoFar)
alert("Please enter the details for your enquiry.")
if (okSoFar==true) submit();
// --></script><input type="button" value="Send" name="B1" ONCLICK="javascript:validateForm()">
You must fill in the fields marked with a *</td>

OK so far, I quite like the idea of checking whether all required fields are filled up with that little javascript function. At first check whether there is an email address with the variable 'foundAt'. Well, actually one might like to use even more validation and check the email address for accuracy using something like that instead:

var goodemail = email.value.match('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.

if (goodemail == 1 && okSoFar) ...

So what's your impression 'bout that. Is it useful to check email address accuracy in detail, as we do not have any concern about any database issues? Anyway, it might be good thing to do. The remaining javascript code is selfevident.

Now the PHP code in the calling file that checks for spam abuse. It starts with three variables later on used to see whether the file was actually prompted from your website.

Then a function is defined validating header injection:
function clean_input_4email($value, $check_all_patterns = true)
$patterns[0] = '/content-type:/';
$patterns[1] = '/to:/';
$patterns[2] = '/cc:/';
$patterns[3] = '/bcc:/';
if ($check_all_patterns)
$patterns[4] = '/\r/';
$patterns[5] = '/\n/';
$patterns[6] = '/%0a/';
$patterns[7] = '/%0d/';
//NOTE: can use str_ireplace as this is case insensitive but only available on PHP version 5.0.
return preg_replace($patterns, "", strtolower($value));

$name = clean_input_4email($_POST["name"]);
$email = clean_input_4email($_POST["email"]);
$thesubject = clean_input_4email($_POST["thesubject"]);
$themessage = clean_input_4email($_POST["themessage"], false);

$error_msg='ERROR - not sent. Try again.';
A confirmation text is outputed and a confirmation mail is send to the author of the message when the input passes this test and another one further down.
$success_sent_msg=' some message'

$replymessage='some message'
Now the biscuits, what we wanted to do in the first place - send an email to the domain admin, support, CRM or what ever through the from. Again the PHP code checks for the email field to be set (see below) and if the form was actually submitted from your domain (here now are the three variables from the start kickin' in. If the referrer don't match you'll be asked to sent the form again, from the right site. If that's all right the mail to you and the inquiring person are sent and the webuser gets an message that verything was fine

if (!isset($_POST['email']))
echo "<script language=\"JavaScript\"><!--\n ";
echo "top.location.href = \"$valid_ref1\"; \n// --></script>";

if($ref_page==$valid_ref1) $valid_referrer=1;
elseif($ref_page==$valid_ref2) $valid_referrer=1;
echo "<script language=\"JavaScript\"><!--\n alert(\"$error_msg\");\n";
echo "top.location.href = \"$valid_ref1\"; \n// --></script>";
$themessage = "name: $name \nQuery: $themessage";
"From: $email\nReply-To: $email");
"Receipt: $thesubject",
"From: $replyemail\nReply-To: $replyemail");
echo $success_sent_msg;

That's an awful lot of code to be posted here, but in comparison with other scipts it is actually quite few. To my rudimentary undestanding of programming and internet security I would assess it as: IT DOES THE JOB. But if I was without concern I wouldn't start a thread here and therefore 'd like to hear some of the advanced voices here on this php mailform.

May 15 '07 #1
3 3015
code green
1,726 Expert 1GB
OK so far, I quite like the idea of checking whether all required fields are filled up with that little javascript function
Ok if the client machine has javascript enabled.
A confirmation text is outputed and a confirmation mail is send to the author of the message
I also send an encrypted code within a hyperlink, with a polite explanation asking the sender to confirm by clicking the link. This at least confirms you are dealing with a genuine address and a genuine (but slightly annoyed) customer.
If the referrer don't match you'll be asked to sent the form again, from the right site
For the determined this can be bypassed with a bogus form. [HTML]var goodemail = email.value.match('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.

if (goodemail == 1 && okSoFar) ...[/HTML]
Email pattern matches always mean you will upset somebody with an obscure address. I was turning away (unknowingly) Gaelic names for about 3 months. The header injection is useful but what about SQL injection? It looks OK. Don't like the reliance on javascript.
May 15 '07 #2
5,821 Expert 4TB
For an in-depth explanation of email-address validation, check out this article:

There's also a decent article here (the site has a really nice reference section):
May 16 '07 #3
To code green,

Well, I gues you prefere validating form input in the PHP file, right?

So something like that would work even if the client hasn't got javascript enabled:


if (empty($_POST['fieldname'])
{ print "<p> Please enter coorect .... </p>":
print "<a href=\"javascript:history.back()\">Back</a>"; }
But then you'd need javascript anyway to go back or you do it all in one file but wouldn't you expose your email address to the public then?

Also, why would you suggest to check for SQL injection? I mean there is no connection to database in the files. Wouldn"t it just extent the script length in vain to check 4 SQL injection?

To pbmods,

Thanks for the link to the javascript email check. It seems a lot easier than my version which does the job however, too. But, that was not really an impression whether the whole thing would pass your assessment as secure mailform, right!!


May 16 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Alexander Ross | last post: by
2 posts views Thread by Joker | last post: by
2 posts views Thread by Andre | last post: by
5 posts views Thread by Henry Stock | last post: by
8 posts views Thread by blaqpig | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.