Contact forms
on web sites are becoming increasingly popular. Rather than use
perl/cgi and running formmail, the easiest and more secure method
is to use a small php script which integrates into your 'thanks'
page.
The web form
First of all,
you need to construct your web form. This should start with the
following...
<form
method="POST" action="thanks.php">
The 'method'
parameter indicates that all variables (data) collected are to be
hidden and not placed in the URL. The most important part is the
'action' parameter as this indicates where the processing of the
form should be done. The form may also be given a name but as this
is optional, I've left it out in this case to keep everything simple.
Our example
form will collect a name and an email address. The following lines
will do this.
Name:
<input type="TEXT" name="name">
Email: <input type="TEXT" name="email">
Then we need
a submit button and a tag to indicate the end of the form.
<input
type="SUBMIT" name="Submit" value="Submit">
</form>
The thanks
page
Once someone
has clicked on the 'Submit' button to submit the details on our
form, we should let them know that their form has been submitted.
For this we need a thanks page. This should be a normal html page
which you will have constructed. You should then rename your thanks
page to 'thanks.php'. The php extension enables the web server to
run the php code on that page before it is sent to the browser.
Under the <BODY>
tag on your thanks page, please enter the following code...
<SCRIPT
LANGUAGE="php">
$email = $HTTP_POST_VARS[email];
$mailto = "email@address";
$mailsubj = "Form submission";
$mailhead = "From: $email\n";
reset ($HTTP_POST_VARS);
$mailbody = "Values submitted from web site form:\n";
while (list ($key, $val) = each ($HTTP_POST_VARS))
{
$mailbody .= "$key : $val\n";
}
mail($mailto, $mailsubj, $mailbody, $mailhead);
</SCRIPT>
Make sure
that you replace 'email@address' in the code with your own email
address.
This code picks
out ALL the data POSTed from the form and sends it to the email
address specified. It's possible to make the code a little more
elaborate in order to detect if an email address hasn't been entered.
It's also possible to add javascript to the form itself to detect
this.
Security considerations
The code above
is quite secure as the email address has been hard-coded into the
php script. You should NEVER pass your email address to the script
as a variable as it's possible that your script could be abused
by other people for their own ends. As a by-product of this, your
email address will not be visible for spammers to collect which
should help with the amount of junk email received.
It's also a
good idea not to output any of the variables you have collected
to the screen unless you can filter out any extra html code. Otherwise,
it may well be possible that someone could enter some malicious
code into the form that would run when the thanks page is loaded.
|