So I have a contact form where customers can fill in their details. When submitted, the form posts the information across to a PHP script that then formats it into html and emails it to my business email.
The only problem I have is that I keep receiving blank emails at random. Obviously the PHP script is being triggered and an email is being sent but I'm not sure why.
The form has required fields so even if someone tried to submit it blank, it wouldnt let them. When I recieve these emails, there should at least be something in them.
I've thought about adding some extra validation to the PHP script to check if any of the required values are empty/missing, but the form deals with this anyway.
Does anyone know what is happening? It's probably something simple i've overlooked.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$budget = $_POST['budget'];
$timeframe = $_POST['timeframe'];
$desc = $_POST['desc'];
//Send HTML formatted email
$send = mail("nathan#nathanthompson.co.uk",
"You have received an enquiry",
"<html>
<body>
<h3>Here is the information for the enquiry: </h3>
<br>
<p>Name: $name</p>
<p>Email: $email</p>
<p>Budget: $budget</p>
<p>Timeframe: $timeframe</p>
<br>
<p>Description of enquiry:</p>
<p>$desc</p>
</body>
</html>
", "Content-type: text/html; charset=iso-8859-1");
if ($send)
{
header("Location:index.html");
}
else
{
echo "An error occurred. Please return to the contact form and try again.";
}
?>
Here you go, try this! :)
<?php
//Check the request method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Start by importing and sanitizing the fields
$name = sanitize($_POST["name"]);
$email = sanitize($_POST["email"]);
$budget = sanitize($_POST["budget"]);
$timeframe = sanitize($_POST["timeframe"]);
$desc = sanitize($_POST["desc"]);
//Make sure the fields are populated
if (empty($name)) {die("The 'Name' field was not populated. Please return to the contact form and try again.");}
if (empty($email)) {die("The 'Email' field was not populated. Please return to the contact form and try again.");}
if (empty($budget)) {die("The 'Budget' field was not populated. Please return to the contact form and try again.");}
if (empty($timeframe)) {die("The 'Time Frame' field was not populated. Please return to the contact form and try again.");}
if (empty($desc)) {die("The 'Description' field was not populated. Please return to the contact form and try again.");}
//Everthing is fine, so send the email!
$send = mail("nathan#nathanthompson.co.uk", "You have received an enquiry",
"<html>
<body>
<h3>Here is the information for the enquiry: </h3>
<br>
<p>Name: $name</p>
<p>Email: $email</p>
<p>Budget: $budget</p>
<p>Timeframe: $timeframe</p>
<br>
<p>Description of enquiry:</p>
<p>$desc</p>
</body>
</html>
", "Content-type: text/html; charset=iso-8859-1");
if ($send) {
header("Location: index.html");
} else {
die("An error occurred. Please return to the contact form and try again.");
}
} else {
die("An error occurred. Please return to the contact form and try again.");
}
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES);
return $data;
}
?>
Related
I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.
I am trying to validate my RSVP form using only PHP. The user should receive an error message when the form is incomplete. I am trying to avoid the use of jQuery.
I am using this tutorial:
http://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
The form is functioning fine but I haven't been able to get the error messages to display at all. I am using Wordpress and I want the form to appear at the footer of every page; not sure if this complicates matters. Here is my code:
<?php
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='success'>{$message}</div>";
} else {
$response = "<div class='error'>{$message}</div>";
}
}
//response messages
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//variables defined for messages
$email = $_POST["rsvp_email"];
$name = $_POST["rsvp_name"];
$attend = $_POST["rsvp_attend"];
$number = $_POST["rsvp_number"];
//variables defined for message to admin
$to = get_option('admin_email'); //sending to wordpress admin email
$subject = "Just Kidding You Foo";
$headers = "From: $email\n";
$message = "$name $attend.\n RSVPs $number of people";
//conditional statements used for form validation
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
my_contact_form_generate_response("error", $email_invalid);
} else { //email is valid
//validate presence of name and message
if(empty($name) || empty($attend) || empty($number)) {
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to,$subject,$message,$headers);
if($sent) {
my_contact_form_generate_response("success", $message_sent); //message sent!
} else {
my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
?>
<div id="page-rsvp">
<h1>RSVP</h1>
<div id="respond">
<?php echo $response; ?>
<form action="<?php the_permalink(); ?>" method="post">
<!--Name here-->
<div class="rsvp-full"><label for="rsvp_name"><input type="text" name="rsvp_name" value="Your name"></label></div>
<div class="rsvp-full"><label for="rsvp_email"><input type="text" name="rsvp_email" value="Your email"></label></div>
<!--status of attendance-->
<div class="rsvp-full">
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="accepts">Accepts</div>
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="declines">Declines</div>
</div>
<!--number of guests attending-->
<div class="rsvp-full"><input type="number" name="rsvp_number" min="1" max="5">Total number of guests attending</div>
<div id="submit-button" class="rsvp-full"><input id="submit-button" type="submit"></div>
</form>
</div>
</div>
TIA!!!
I'm not that familiar with WP, but if I understand correctly, I believe you're trying to ensure all the fields are filled out.
Check your brackets! You need to be sure your curly brackets are opening and closing where you want them to. Otherwise the output of the page won't display. I write in all my braces because I'm not smart enough to be sure I know where they start and stop. I've taken the liberty of editing them into your question. I believe there was one missing at the end.
Once I fixed the brackets and removed functions my computer didn't have, it worked fine.
Tip 0: Try turning error reporting on for this script - error_reporting(E_ALL); at the top of this script. I always do for development.
Tip 1: use the placeholder attribute instead of value for things like "your name".
Tip 2: make sure the $_POST vars are set. I would do this by checking if they're set and then setting them to '' if they aren't; something like this:
//variables defined for messages
// you could do it like this:
if (isset($_POST["rsvp_email"])) {
$email = $_POST["rsvp_email"];
} else {
$email = '';
}
// or like this:
$name = '';
if (isset($_POST["rsvp_name"])) {
$name = $_POST["rsvp_name"];
}
// or even using a ternary operator:
$attend = isset($_POST["rsvp_attend"]) ? $_POST["rsvp_attend"] : '';
//but this will trigger a "Notice" error if the post var isn't set.
$number = $_POST["rsvp_number"];
im having issues with my script not sending an email, the return error message is: Email address not valid! This happens when ever I enter my email address into the text field. I have a feeling that it is the (preg_match) method that is creating the issue, but after looking online I dont really understand the content of the method. Hope you guys can help, thanks.
SOURCE CODE:
<?php
/*Select email recipient*/
$myemail = "info#shadowempires.url.ph";
/*Check all form inputs using check input function*/
$name = check_input($_POST['name'], "Please enter your name");
$email = check_input($_POST['email'], "Please enter your email address.");
$comment = check_input($_POST['comment'], "Please write a message.");
/*If email is not valid show error message*/
if (!preg_match("/(\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
show_error("Email address not valid!");
}
/*Lets prepare the message for the email*/
$message = "Customer Question!
Contact form has been submitted by:
Name: $name
Email: $email
Comments: $comment
End of message";
/*Send the message using mail() function*/
mail($myemail, $message);
/*Redirect visitor to the thank you page*/
header('Location: thankyou.htm');
exit();
/*Functions we used*/
function check_input($data, $problem=''){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0){
show_error($problem);
}
return $data;
}
function show_error($myError){
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php exit();
}
?>
What about filter_var:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid email address
}
This is an easy way to validate an email address.
UPDATE 1
Take a look to this answer. Here there is more information about using regex for validate email address: How to validate an email address in PHP
UPDATE 2
There is a tool for test regex email patterns, look here
You need to fix your regexp, here is example of working one:
/((\w|\-))+\#((\w|\-))+\.((\w|\-))+/
I am creating an admin page, where the admin person can create users accounts for people. The idea is, that once the form is completed, when clicking 'Submit' an email must be sent to the user (containing the ID and name of account selected). In the same action, the form must also first be validated and if there are any errors with the validation the data should not be submitted to the database. None of this is happening though and I cannot figure out why.
The email is not being sent,
the data is inserted in the database even if there are errors and upon loading the page,
errors are displayed for all form fields even though the submit button have not been clicked.
Any help, advice or links to possible sources/tutorials would be greatly appreciated.
Below is my code: (Note that I am only working in PHP, HTML and using a MYSQL database)
<html>
<head>
<title>
User Registration
</title>
<?PHP
include_once 'includes\functions.php';
connect();
error_reporting(E_ERROR | E_PARSE);
//Assign variables
$accounttype=mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
//Validating form(part1)
$error='';
//Connect to database
$SQL=
"INSERT INTO student
(
sname,fname,email, address, contact_flag
)
VALUES
(
'$sname', '$fname', '$email', '$address', '$contact_flag'
)
";
if (!mysql_query($SQL))
{
print'Error: '.mysql_error();
}
mysql_close($db_handle);
//Validate form(part 2)
if (isset($_POST['sname'], $_POST['fname'],$_POST['email'],$_POST['address']));
{
$errors=array();
$accounttype= mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
// form validation
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE)
{
$errors[]='Please insert your valid email address';
}
if(strlen(mysql_real_escape_string($address))<8)
{
$errors[]='Please insert your postal address';
}
echo'<pre>';
print_r($errors);
echo'</pre>';
}
//confirmation email
// Subject of confirmation email.
$conf_subject = 'Registration confirmed';
// Who should the confirmation email be from?
$conf_sender = 'PHP Project <my#email.com>';
$msg = $_POST['fname'] . ",\n\nThank you for registering. \n\n You registered for account:".$accounttype."\n\n Your account number:".mysql_insert_id;
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
?>
</head>
<body>
</br>
<form name ="form0" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<b>Select the course you wish to register for:</b></br>
<select name="accounttype">
<?PHP query() ?>
</select>
<?PHP close() ?>
</form>
<form name ="form1" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<Input type ="" Value = "Surname" Name = "sname"></br>
<Input type ="" Value = "First name" Name = "fname"></br>
<b>Email:</b> <Input type ="" Value = "" Name = "email"></br>
<b>Address:</b> </br>
<textarea rows="4" cols="20" Name="address">Please provide your postal address here </textarea></br>
<b>Tick to receive confinmation email:</b> <Input type ="checkbox" Value = "1" Name = "contact_flag"></br>
<Input type = "Submit" Value="Submit">
</form>
</body>
</html>
<?PHP
if(isset($_POST['submit']))
{
include_once 'includes\functions.php';
connect();
// your rest of the code
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
}
?>
and keep this code out of the <html> tag but before it
and if you want to stick to PHP only then one error i can see is
that you have kept the **validation code below the `INSERT`**
query which means that the insert query will be executed first which will store the data in the database first and then it will go for the validation...so keep your validation code above the INSERT statement..
and second thing use exit() method after vaidating every field if it gives you error...it will stop executing rest of the php code if any field gives the error during validation....and so it will also prevent the data from storing into the database if it finds exit method whenever an error is found eg
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
echo '//whatever you want to echo';
exit();
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
echo '//whatever you want to echo';
exit();
}
At first, your query gets executed before you validate your form.
Move your SQL after your
echo'<pre>';
print_r($errors);
echo'</pre>';
and surround it with
if(!$errors){}
This will prevent your query from being executed if there are any errors.
(You can also delete your first assignement of your variables)
Concerning your email problem, test your connection with a simple message
mail('your#email.com', 'subject', 'message');
If you get any error, probably your mailserver isn't set up right
I have looked for similar questions and I did not find my particular case.
I am using the PHP Captcha plugin within a form that I have. I handle the incorrect and correct captcha entries very similar. If the user's phrase is correct I throw a javascript "success" alert, send the form email, and then send them back to the last page. If incorrect I throw a javascript "your incorrect" alert and send them back to the last page.
My problem- if they are incorrect I need to refresh Captcha because with an incorrect Captcha entry you will always need to refresh the image for another attempt. Also if they are correct I want the field cleared but only cleared when correct, if incorrect I want to keep the forms data. How can I do this?
Here is my PHP captcha code so you can see my attempt. Let me know if you want the html... (also I checked all entries with JS before POST)
<?php
/*set email*/
$myemail = "email#email.com";
/* Check all form inputs using check_input function */
$name = $_POST['name'];
$companyName = $_POST['companyName'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$TimeForContact = $_POST['TimeForContact'];
$aval = $_POST['aval'];
$messageFromFrom = $_POST['message'];
$firstTime = $_POST['firstTime'];
$subject = "Some Subject";
require_once('recaptcha-php-1.11/recaptchalib.php');
$privatekey = "*someprivatekey*"; //I took this out for the question
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo '<script type="text/javascript"> alert ("You have inserted the wrong phrase in the Captcha box. Please try again! Thank you."); window.history.back();</script>';
exit();
} else {
$message = "some message
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
echo '<script type="text/javascript"> alert ("Success! You have emailed your submission. Please await our response. Thank you."); window.history.back()</script>';
exit();
}
?>
I originally tried reloading the page through JS, like:
window.reload(history.back());
or
window.location.reload(history.go(-1));
no success with either + multiple combinations similar to that.
So to reiterate the question:
How can I refresh form/captcha when desired
OR
What is your practiced behavior for submitting a captcha form?
Thank you.
You should be doing something like this. Essentially checking for errors and pushing errors into an error array that you can later loop over and display to the user. Upon submit, you check the recaptcha and if its invalid, it will automatically clear the field. Do not use alerts or exit() or anything of that sort, a simple $errors array should suffice.
//untested code
<?php
//check to make sure they submitted the form
if(isset($_POST['submit'])){
$errors = array();
$myemail = "email#email.com";
$name = $_POST['name'];
$companyName = $_POST['companyName'];
/* ... */
//recaptcha check
require_once('recaptcha-php-1.11/recaptchalib.php');
$privatekey = "*someprivatekey*";
$resp = recaptcha_check_answer (
$privatekey,$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
//validate all data here
if (!$resp->is_valid) {
array_push($errors, "recaptcha invalid please try again");
}else if( /* name is invalid */) {
array_push($errors, "name invalid");
}else if (){
/* keep validing ...... with else if*/
}
/*....*/
else{
//everything validated so were good
mail($myemail, $subject, $message);
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="process.php">
<!-- Your form here, "process.php" is this page itself -->
<input name="submit" type="submit" value="Send">
</form>
</body>
</html>