simple php captcha contact form - php

i am trying to create simple contact form with captcha in php. However it turns out implementing captcha is out of my league.
I found a simple answer on stackoverflow opn similar problem which pushed me 1 step closer to the end, but again i got stuck.
So i need a contact form that only check if text is entered and if correct captcha is answered, email is not mandatory.
</br>
<?php
$a=rand(2,9);
$b=rand(2,9);
$c=$a+$b;
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha == $c )) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
} else {
echo 'Neteisingai užpildyta forma.';
}
}
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php echo $a."+".$b."="?><input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input type="submit" value="Siusti">
<br>
</form>
Now the problem is that I always get the message that details are incorrect. I tried to echo recaptcha just to see if $c is correct and it works. But for some reason not able to compare $recaptcha with $c or some other issue I am not sure.

The value of $c will be a completely different value when the user submits the contact form vs when your validation checks it. The value will change on every request because the script is re-interpreted.

You will have to save the value of $c on the initial page load, so that you can compare it afterwards in the next request. You can do that by storing it in $_SESSION.

You can write this
<?php
$min_number = 2;
$max_number = 9;
$random_number1 = mt_rand($min_number, $max_number);
$random_number2 = mt_rand($min_number, $max_number);
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$firstNumber = $_POST["firstNumber"];
$secondNumber = $_POST["secondNumber"];
$checkTotal = $firstNumber + $secondNumber;
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha != $checkTotal )) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
} else {
echo 'Neteisingai užpildyta forma.';
}
}
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php
echo $random_number1 . ' + ' . $random_number2 . ' = ';
?>
<input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input name="firstNumber" type="hidden" value="<?php echo $random_number1; ?>" />
<input name="secondNumber" type="hidden" value="<?php echo $random_number2; ?>" />
<input type="submit" value="Siusti">
<br>
</form>
This might solve your problem

you should to use session to solve your problem, i did little changes in your code, it should to work perfectly.
<?php
#session_start();
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha == $_SESSION["captcha"])) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
}else{
echo 'Neteisingai užpildyta forma.';
}
}else{
$a=rand(2,9);
$b=rand(2,9);
$c=$a+$b;
//setting captcha code in session
$_SESSION["captcha"] = $c;
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php echo $a."+".$b."="?><input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input type="submit" value="Siusti">
<br>
</form>
<?php
}
?>

Related

How can I add a success message to my mail form code?

I tried using echo but something's wrong in that echo area.
I got syntax errors and and an error saying unexpected token afterecho "Try again."
<?php
add_action("admin_menu", "addMenu");
function addMenu()
{
add_menu_page("smail", "smail", 4, "smail", "sMail" );
}
function sMail()
{
?>
<h2> send mail</h2>
<form method="post" action="">
<?php
if(isset($_POST['submit'])){
$to = sanitize_email( $_POST['email_address'] );
$subject = sanitize_text_field( $_POST['subject'] );
$txt = esc_textarea( $_POST['text'] );
$from = sanitize_email( $_POST['frommail'] );
$headers = "From:" . $from ;
if (mail($to,$subject,$txt,$headers)){
echo "Mail sent successfully.";
} else{
echo "Try again.";
}
}
?>
<label for="frommail">From </label>
<input id="frommail" name="frommail" type="text" maxlength="255" />
<label for="email_address">To </label>
<input id="email_address" name="email_address" type="text" maxlength="255"/>
<label for="subject">Subject </label>
<input id="subject" name="subject" type="text" maxlength="255" />
<label for="text">Text </label>
<textarea id="text" name="text" row="10"></textarea>
         <input value="submit" id="submit" name="submit" type="submit">
</form>
<?php
}
?>
Please don't define functions like in your sMail function.
If you want to print out html content, use echo instead.
You also miss a } from end of file.
Also:
If you want to use the current script for your action path, just leave out the action tag.
Here's your corrected code:
<?php
add_action("admin_menu", "addMenu");
function addMenu()
{
add_menu_page("smail", "smail", 4, "smail", "sMail");
}
function sMail()
{
echo " <h2> send mail</h2> ";
echo " <form method='post' action=''> ";
if (isset($_POST['submit']))
{
$to = sanitize_email($_POST['email_address']);
$subject = sanitize_text_field($_POST['subject']);
$txt = esc_textarea($_POST['text']);
$from = sanitize_email($_POST['frommail']);
$headers = "From:" . $from;
if (mail($to, $subject, $txt, $headers))
{
echo "Mail sent successfully.";
}
else
{
echo "Try again.";
}
}
}
?>

WordPress custom Contact Form in Bootstrap modal is not showing validation & submission response

For my WordPress (v5.5.1) I am using Bootstrap and built a Custom Contact Form in Bootstrap Modal with below HTML (followed this tutorial: https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/).
<form id="contact-form" action="<?php echo get_site_url(); ?>" method="post">
<div class="modal-body">
<?php echo $response; ?>
<div class="form-group">
<input class="form-control my-2" type="text" name="message_name" size="50" placeholder="Your full name" value="<?php echo esc_attr($_POST['message_name']); ?>">
<input class="form-control my-2" type="email" name="message_email" size="50" placeholder="Email address" value="<?php echo esc_attr($_POST['message_email']); ?>">
<input class="form-control my-2" type="tel" name="message_tel" size="50" placeholder="Country code, Phone number" value="<?php echo esc_attr($_POST['message_tel']); ?>">
<textarea class="form-control my-2" name="message_text" rows="2" placeholder="Your message" value="<?php echo esc_attr($_POST['message_text']); ?>"></textarea>
<input class="form-control my-2" type="text" name="message_human" placeholder="Human check: Enter 2">
<input type="hidden" name="message_url" value="<?php the_permalink(); ?>">
<input type="hidden" name="message_page" value="<?php the_title(); ?>">
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="submitted" value="1">
<button type="submit" value="Submit" class="btn btn-search form-control">Send Enquiry</button>
</div>
Below the function to validate the Forms & show responses while Form submission:
function validateform() {
//response generation function
$response = "";
//function to generate response
function contact_g_form_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
}
//response messages
$not_human = "Enter current year in numbers.";
$missing_content = "Missing something.";
$email_invalid = "Check your Email address.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! We got your enquiry.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$fromEmail = $name . '<' . $email . '>';
$tel = $_POST['message_tel'];
$text = $_POST['message_text'];
$url = $_POST['message_url'];
$page = $_POST['message_page'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = '[General Enquiry] ' . $name . ' | Phone Number:' . $tel;
$headers = 'From: ' . $fromEmail . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$message = '<html><body><h1>New general enquiry from ' . $name . '!</h1>'
. '<p>Email: ' . $email . '</p>'
. '<p>Phone Number: ' . $tel . '</P>'
. '<p>Inquiry: ' . $text . '</P>'
. '<p>From page: <b>' . $page . '</b></P>'
. '<p>Page URL: ' . $url . '</p>'
. '</body></html>';
if (!$human == 0) {
if ($human != 2) {
contact_g_form_response("error", $not_human); //not human!
} else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
contact_g_form_response("error", $email_invalid);
} else { //email is valid
//validate presence of name, phone number
if (empty($name) || empty($tel)) {
contact_g_form_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to, $subject, $message, implode("\r\n", $headers)); //mail to admin - striptags removing formatting
// $sent2 = wp_mail($email, $subject, $body, $headers); //mail to visitor
// if ($sent || $sent2) {
if ($sent) {
contact_g_form_response("success", $message_sent); //message sent!
} else {
contact_g_form_response("error", $message_unsent); //message wasn't sent
}
}
}
}
} else if ($_POST['submitted']) {
contact_g_form_response("error", $missing_content);
}
}
In the earlier versions of WordPress the email was being sent without validation, with v5.5.1 upgrade, the Modal is closing without any validation and the email is also not being sent.
You Just Need To replace this:
<form id="contact-form" action="<?php echo get_site_url();?>" method="post">
With This:
<form id="contact-form" method="post">
Because You are displaying the error on the same page but on click of the submit button the action is taking you to a specific url and that's the reason the validations are not shown.
And This:
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
With This also:
if ($type == "success") {
$response = $message;
echo $response;
} else {
$response = $message;
echo $response;
}

Contact form with required fields will not submit - using PHP validation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My contact form will not submit and send to my email address..
Here is the PHP validation I am using to check required fields and then to send to my email:
<?php
if (isset($_GET['submit'])) {
$body = '';
$body .= 'Name: ' . $_POST['name'] . "\n\n";
$body .= 'Phone: ' . $_POST['phone'] . "\n\n";
$body .= 'Email: ' . $_POST['email'] . "\n\n";
$body .= 'Message: ' . $_POST['message'] . "\n\n";
mail('myemailaddress#gmail.com', 'Contact Form', $body, 'From: no-reply#mycompany.com');
}
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $spamcheckErr = "";
$name = $address = $email = $message = $spamcheck = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
if (!isset($_POST["spamcheck"])) {
$spamcheckErr = "Verify you are not spam.";
}
else {
$spamcheck = $_POST["spamcheck"];
}
}
?>
Here is my HTML:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="contact_input" class="col1">
<input name="name" placeholder="Name*" type="text" class="text" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span><br />
<input name="email" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span><br />
<input name="phone" placeholder="Phone #" type="tel" class="text" value="<?php echo $phone;?>" />
</div>
<div id="contact_input" class="col2">
<textarea name="message" placeholder="Message*" rows="10" cols="25"><?php echo $message?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div>
<div id="contact_input" class="col3">
<input id="spamcheck" type="checkbox" name="spamcheck" value="<?php echo htmlspecialchars($spamcheck);?>">I am human.*<br />
<span class="error"><?php echo $spamcheckErr;?></span>
<input id="submit" type="submit" name="submit" value="Send" class="button" /><br />
<span>*Required Field.</span>
</div>
</form>
When fields are empty I get the proper error message under each field but I cannot get it to send to my email. However it was emailing me every time I loaded the page, when I made these changes it stopped submitting.
Being new to contact forms with required fields, I can't seem to find the clear answer elsewhere.
I suspect it has something to do with if (isset($_GET['submit'])) Since that is where I made the change and started having issues.
You have to add ?submit to the action string in your form or else $_GET['submit'] will be unset.
<form method="post" action="?submit">
or you can change the isset function to check the $_POST var instead of the $_GET var
if (isset($_POST['submit'])) {
EDIT: Here's what you should do with your validation script
if (!empty($_POST['submit'])) {
$error = array();
if (empty($_POST['email'])) $error[] = 'Please enter your email';
// and so on...
if (empty($error)) {
// Send email script goes here
}
}
And then for your user display upon any errors:
if (!empty($error)) foreach ($error as $e) echo '<p class="error">'.$e.'</p>';
This allows you to add more error messages as often as you'd like with ease, and uses the empty property of an array to verify the lack of error in validation.
I tested your code and everything checked out, except for this line:
if (isset($_GET['submit'])) {
which just needs to be changed to:
if (isset($_POST['submit'])) {
The issue was in fact using $_GET instead of $_POST
EDIT
Added a few conditional statements:
if (($_POST['name'] && $_POST['email'] && $_POST['message'] !="")
&& isset($_POST["spamcheck"]) !="")
Full code (use the full version below):
<?php
if (isset($_POST['submit'])) {
$body = '';
$body .= 'Name: ' . $_POST['name'] . "\n\n";
$body .= 'Phone: ' . $_POST['phone'] . "\n\n";
$body .= 'Email: ' . $_POST['email'] . "\n\n";
$body .= 'Message: ' . $_POST['message'] . "\n\n";
if (($_POST['name'] && $_POST['email'] && $_POST['message'] !="") && isset($_POST["spamcheck"]) !="")
{
mail('myemailaddress#gmail.com', 'Contact Form', $body, 'From: no-reply#mycompany.com');
}
}
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $spamcheckErr = "";
$name = $address = $email = $message = $spamcheck = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
if (!isset($_POST["spamcheck"])) {
$spamcheckErr = "Verify you are not spam.";
}
else {
$spamcheck = $_POST["spamcheck"];
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="contact_input" class="col1">
<input name="name" placeholder="Name*" type="text" class="text" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span><br />
<input name="email" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span><br />
<input name="phone" placeholder="Phone #" type="tel" class="text" value="<?php echo $phone;?>" />
</div>
<div id="contact_input" class="col2">
<textarea name="message" placeholder="Message*" rows="10" cols="25"><?php echo $message?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div>
<div id="contact_input" class="col3">
<input id="spamcheck" type="checkbox" name="spamcheck" value="<?php echo htmlspecialchars($spamcheck);?>">I am human.*<br />
<span class="error"><?php echo $spamcheckErr;?></span>
<input id="submit" type="submit" name="submit" value="Send" class="button" /><br />
<span>*Required Field.</span>
</div>
</form>
I don't understndand if (isset($_GET['submit'])) in fact. Why is it there?
$field1 = NULL;
$field2 = NULL;
if(isset($_POST["submit"])){
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
//etc
mail ("youremail", "yoursubject", "$field1 $field2 $field3 etc.");
}

My PHP form submits but does not validate the email address

I am an eager novice with PHP so please forgive my errors as I am learning as I go. Basically, I am building a simple contact form for my website and have successfully been able to have the form send the user's first and last name, subject, email address and message. I am using a second file, "form_process.php" to process the form data from "index.php".
The problem is that the email address does not seem to be validating and will send any words typed. I would greatly appreciate it if some more seasoned eyes could take a look and help me sort this out. Thank you in advance.
Michael.
HTML:
<div id="form">
<form action="form_process.php" method="post" enctype="multipart/form-data">
<p>
<input type="text" maxlength="100" size="50" name="fName" value="<?php echo $stored_fName;?>" placeholder="First Name" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="lName" value="<?php echo $stored_lName;?>" placeholder="Last Name" />
</p>
<p>
<input type="text" maxlength="80" size="50" name="email" value="<?php echo $stored_email;?>" placeholder="Email Address" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="subject" value="<?php echo $stored_subject;?>" placeholder="Subject" />
</p>
<p>
<textarea name="message" rows="6" cols="38" placeholder="Message"></textarea>
</p>
<br />
<input type="submit" value="Submit" name="submit" />
<input type="reset" value="Clear" name="clear">
</form>
</div>
<!-- form ends -->
PHP: "form_process.php"
<?php
session_start();
// Report all PHP errors
error_reporting(E_ALL);
//use $_POST to to store data from submitted form into these variables
$fName = check_input($_POST['fName']);
$lName = check_input($_POST['lName']);
$sender = check_input($_POST['email']);
$subject = check_input($_POST['subject']);
$message = check_input($_POST['message']);
//check_input function to strip unnessessary characters and sanitize user data
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = $fName ." ". $lName;//concatenating first and last names to new name variable
$sanitizedEmail = filter_var($sender, FILTER_SANITIZE_EMAIL);
//generates error messages on index.php if form fields left blank
if ($fName == ''){
header("Location:index.php?message=1");
exit();
}
if ($lName == ''){
header("Location:index.php?message=2");
exit();
}
if ($sender == ''){
header("Location:index.php?message=3");
exit();
}
if ($subject == ''){
header("Location:index.php?message=4");
exit();
}
if ($message == ''){
header("Location:index.php?message=5");
exit();
}
//headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= $name . "\r\n";
$headers .= "From:" . " " . $sanitizedEmail . "\r\n";
//mail function
$to = "me#myemail.com";
$subject = $subject;
$message = $message;
//send message
$send_message = mail($to,$subject,$message,$headers);
if($send_message){
header("Location:index.php?message=6");
}else {
header("Location:index.php?message=9");
exit();
}
?>
"index.php" error messages:
<?php
//all fields empty until user inputs data for session to store
$stored_fName = '';//init as NULL
$stored_lName = '';//init as NULL
$stored_email = '';//init as NULL
$stored_subject = '';//init as NULL
$stored_message = '';//init as NULL
//session data used to repopulate form fields if any info is missing or incorrect
if (isset($_SESSION['fName'])){
$stored_fName = $_SESSION['fName'];
}
if (isset($_SESSION['lName'])){
$stored_lName = $_SESSION['lName'];
}
if (isset($_SESSION['email'])){
$stored_email = $_SESSION['email'];
}
if (isset($_SESSION['subject'])){
$stored_subject = $_SESSION['subject'];
}
if (isset($_SESSION['message'])){
$stored_message = $_SESSION['message'];
}
//error messages displayed to user if text fields have been left blank
$_GET['message'];
if ($_GET['message'] == 1) {//first name
echo "<strong>Please type your first name.</strong>";
}
if ($_GET['message'] == 2) {//last name
echo "<strong>Please type your last name.</strong>";
}
if ($_GET['message'] == 3){//email address
echo "<strong>Please type an email address.</strong>";
}
if ($_GET['message'] == 4){//subject
echo "<strong>Please type a subject.</strong>";
}
if ($_GET['message'] == 5){//message text
echo "<strong>Please type your message.</strong>";
}
if ($_GET['message'] == 6){//message success from form_process.php
echo "<strong>Your message was sent successfully. Thank you.</strong>";
}
if ($_GET['message'] == 9){
echo "<strong>I'm sorry but your message was not sent. Please try again, thank you.</strong>";
}
?>
You should be using it like this:
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
// is email
$sender = $email;
}else{
// isn't email
$sender = '';
}
Read more about PHP Validate Filters

PHP Trying to add ability to send attachment to working contact us form

I have a friend who asked me to modify her website's contact form to request phone number and also the ability to add photo attachments. I've added the code necessary to request and send the phone number with the email, but adding the ability to attach photo files is beyond the current scope of my knowledge. Could someone take a look at the code and tell me how to add the ability to attach files to the message? All I'm trying to do is add this below the current message field, but it's proving to be more involved than I expected. Since everything I tried has broken the current form, I've removed my code attempts to add the attachment and I'm posting the code as it currently works. It's my hope someone with a better grasp of php can help us with this.
<?php
//set the level of error reporting
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
// Set-up these 3 parameters
$to = 'any#somewhere.net';
$subject = 'Question from The website';
$contact_submitted = 'Your message has been sent.';
function email_is_valid($email) {
return preg_match('/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i',$email);
}
if (!email_is_valid($to)) {
echo '<p style="color: red;">You must set-up a valid (to) email address before this contact page will work.</p>';
}
if (isset($_POST['contact_submitted'])) {
$return = "\n\r";
$youremail = trim(htmlspecialchars($_POST['your_email']));
$yourname = stripslashes(strip_tags($_POST['your_name']));
$yourphone = trim(htmlspecialchars($_POST['your_phone']));
$yourmessage = stripslashes(strip_tags($_POST['your_message']));
$contact_name = "Name: ".$yourname;
$contact_email = "Email Address: ".$youremail;
$contact_phone = "Phone: ".$yourphone;
$message_text = "Message: ".$yourmessage;
$user_answer = trim(htmlspecialchars($_POST['user_answer']));
$answer = trim(htmlspecialchars($_POST['answer']));
$message = $contact_name . $return . $contact_email . $return . $contact_phone . $return . $return . $message_text;
$headers = "From: ".$youremail;
if (email_is_valid($youremail) && !eregi("\r",$youremail) && !eregi("\n",$youremail) && $yourname != "" && $yourphone != "" && $yourmessage != "" && substr(md5($user_answer),5,10) === $answer) {
mail($to,$subject,$message,$headers);
$yourname = '';
$youremail = '';
$yourphone = '';
$yourmessage = '';
echo '<p style="color: blue;">'.$contact_submitted.'</p>';
}
else echo '<p style="color: red;">Please enter your name, a valid email address, your message and the answer to the simple maths question before sending your message.</p>';
}
$number_1 = rand(1, 9);
$number_2 = rand(1, 9);
$answer = substr(md5($number_1+$number_2),5,10);
?>
<form id="contact" action="contact.php" method="post">
<div class="form_settings">
<p><span>Name:</span><input class="contact" type="text" name="your_name" value="<?php $yourname; ?>" /></p>
<p><span>Email Address:</span><input class="contact" type="text" name="your_email" value="<?php $youremail; ?>" /></p>
<p><span>Phone Number:</span><input class="contact" type="text" name="your_phone" value="<?php $yourphone; ?>" /></p>
<p><span>Message:</span><textarea class="contact textarea" rows="1" cols="50" name="your_message"><?php $yourmessage; ?></textarea></p>
<p style="line-height: 1.7em;">To help prevent spam, please enter the answer to this question:</p>
<p><span><?php echo $number_1; ?> + <?php echo $number_2; ?> = ?</span><input type="text" name="user_answer" /><input type="hidden" name="answer" value="<?php echo $answer; ?>" /></p>
<p style="padding-top: 15px"><span> </span><input class="submit" type="submit" name="contact_submitted" value="send" /></p>
</div>
</form>
If anyone can figure this out I'd be forever grateful.
First problem you're going to have is that you're not going to be able to upload any file without indicating the
enctype="multipart/form-data"
within the form tag.
The rest of the info, you could refer to this tutorial

Categories