Thursday, November 4, 2010

PHP CONTACT FORM

Every website needs a way of contacting the people behind it and putting an email on a page is not such a good idea; because bots can easily pick up this email address and send spam to it. This is where a contact form comes in very useful because people can send you messages but do not get your email address.
For a contact form the first thing that we need to do is to create a form using HTML so that they can input their information and message that they are going to send.
<form action="send_message.php" method="POST">
 Name: <input type="text" name="name"> <br />
 Email: <input type="text" name="email"> <br />
 Message: <textarea name="message"></textarea> <br />
 <input type="submit" name="send_message" value="Send!">
</form>
When the press send it will then go to a page called send_message.php. This page will grab the information that they input and send it to an email address using the mail() function in PHP.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
 
$to = 'your_address@your_email.com';
$subject = "New message from $name";
 
mail($to, $subject, $message, "From: $email");
echo "Message sent";
?>
We need to check that the sender of the message is human so we will add a simple math question to the bottom of our form.
<?php
 
 $num_one = rand() % 10;
 $num_two = rand() & 10;
 $final_num = $num_one + $num_two;
 $_SESSION['answer'] = $final_num;
 echo $num_one . ' + ' . $num_two . ' = ';
 ?>
    <input type="text" name="answer" /> <br />
Don't forget to add
<?php
session_start();
?>
To the top of the page or we will get errors.
Now we check to see if they have entered information into every field and that the answer to the math question is correct, if it is the message will be sent otherwise an error will be returned.
All the code for the form is:
<?php
session_start();
?>
<form action="send_message.php" method="POST">
 Name: <input type="text" name="name"> <br />
 Email: <input type="text" name="email"> <br />
 Message: <textarea name="message"></textarea> <br />
    <?php
 
 $num_one = rand() % 10;
 $num_two = rand() & 10;
 $final_num = $num_one + $num_two;
 $_SESSION['answer'] = $final_num;
 echo $num_one . ' + ' . $num_two . ' = ';
 ?>
    <input type="text" name="answer" /> <br />
 <input type="submit" name="send_message" value="Send!">
</form>
All the code for error checking and sending the message is:
<?php
session_start();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$user_answer = $_POST['answer'];
$real_answer = $_SESSION['answer'];
 
$to = 'your_address@your_email.com';
$subject = "New message from $name";
 
if(empty($name) OR empty($email) OR empty($message)) {
 echo "Fill in all fields.";
} elseif($user_answer != $real_answer) {
 echo "Math question was incorrect, please try again";
} else {
 mail($to, $subject, $message, "From: $email");
 echo "Message sent";
}
?>

No comments:

Post a Comment