contact.php
- Code: Select all
<form action="process.php" method="post">
<table style="border:none; width:100%;">
<tr>
<td>Your name</td><td>
<input type="text" name="name" size="30" class="formf" />
</tr>
<tr>
<td>Your email</td>
<td>
<input type="text" name="email" size="30" class="formf" />
</tr>
<tr>
<td>Your Message</td>
<td><textarea name="message" cols="70" rows="8"></textarea>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="submit" value="send" class="formf" /></td>
</tr>
</table></form>
Ok, the form action points to process.php so now we'll create that.
process.php
- Code: Select all
if(isset($_POST['submit'])){
$problem = FALSE;
if(empty($_POST['name'])){
$problem = TRUE;
echo "Please enter your name.\n";
}
if(empty($_POST['email'])){
$problem = TRUE;
echo "Please enter your email address.\n";
}
if(empty($_POST['message'])){
$problem = TRUE;
echo "Please enter your message.\n";
}
if(!$problem){
$n = $_POST['name'];
$e = $_POST['email'];
$m = $_POST['message'];
$m .= "From " . $e . "\n";
$m .= "(" . $n . ")\n";
if(mail("example@email.com", "Your Contact Form", $m)){
echo "Your email was successfully sent!\n";
}
else
{
echo "There was an error sending the message, please try again!\n";
}
}
}
else
{
echo "Oops, looks like you didn't submit the form, <a href=\"contact.php\">go back and fill it in!</a>\n";
}
First, we create a boolean variable called problem, this we will use later on to check whether we can continue to send the message.
The next 3 if() statements are just checking whether the fields in the form are empty. Now, we use the $problem and if it is false then we will continue with the process.
Now the next lines are assigning variables to the field values that were submitted with the form. Where:
$n represents the name.
$e represents the email.
$m represents the message.
We also add a little bit to the extra to the message just to let the reciever of the message know what email address it was from and what the name of the user that submitted the form was.
Now we check if an email was sent using the mail() function. Here are the parameters for the function.
1. example@email.com - The address which the email should be sent to.
2. Your Contact Form - The subject of the email.
3. $m - The message, this variable is set earlier on.
Then if the email is sent, we display a message to show it's sent and otherwise we throw up an error message.
If you are going to use this on your website, I would suggest some anti-spam methods such as CAPTCHA. See here for some tutorials on captcha.
Thanks.
