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>
<?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"; ?>
<?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 />
<?php session_start(); ?>
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>
<?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