Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
HTML for my fields and contact block, my fields are Name, Number. Email, Subject, Message. All of my fields work properly and when submitted I receive the email perfectly, apart from the Number field which for some reason does not populate with the amount or any value at all
<!-- contact section -->
<div class="container">
<div class="section-header">
<h2 class="wow fadeInDown animated">Contact Us</h2>
<p class="wow fadeInDown animated">Please fill in your contact details below and we will get back to you.<br>Alternatively contact us on: 031 464 4801 | 083 555 1202</p>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2 conForm">
<form method="post" action="php/email.php" name="cform" id="cform" onsubmit="return checkform(this);">
<div id="message"></div>
<input name="name" id="name" type="text" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Your name..." >
<input name="cell" id="cell" type="number" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Your Number..." >
<input name="email" id="email" type="email" class=" col-xs-12 col-sm-12 col-md-12 col-lg-12 noMarr" placeholder="Email Address..." >
<textarea name="comments" id="comments" cols="" rows="" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Message..."></textarea>
<!-- START CAPTCHA -->
<br>
<div class="capbox">
<div id="CaptchaDiv"></div>
<div class="capbox-inner">
Type the above number:<br>
<input type="hidden" id="txtCaptcha">
<input type="text" name="CaptchaInput" id="CaptchaInput" size="15"><br>
</div>
</div>
<br><br>
<!-- END CAPTCHA -->
<input type="submit" id="submit" name="send" class="submitBnt" value="Send">
<div id="simple-msg"></div>
</form>
<script type="text/javascript">
// Captcha Script
function checkform(theform){
var why = "";
if(theform.CaptchaInput.value == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(theform.CaptchaInput.value != ""){
if(ValidCaptcha(theform.CaptchaInput.value) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
// Validate input against the generated number
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('CaptchaInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</div>
</div>
</div>
This is the PHP which pushes the mail, values and email format through to my address, again, everything seems to be in order and works fine, apart from the number (cell) field, which does not populate with any information, no matter what you put into it.
<?php
session_cache_limiter( 'nocache' );
$to = "bjorn#tech5.co.za"; //Recipient's E-mail
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = 'Name: ' . $_REQUEST['name'] . "<br>";
$message .= 'Number: ' . $_REQUEST['cell'] . "<br>";
$message .= 'Email: ' . $_REQUEST['email'] . "<br>";
$message .= $_REQUEST['comments'];
if (#mail($to, 'New Inquiry from Executive Plant Hire', $message, $headers))
{
mail('bjorn#tech5.co.za', 'New Inquiry from Executive Plant Hire', $message, $headers);
// Transfer the value 'sent' to ajax function for showing success message.
echo '<label class="lbl lbl-success">Your email has been sent successfully, we will be in touch</label>';
// header('Location: ../index.html');
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo '<label class="lbl lbl-warning">There was a problem sending you request, please contact us directly</label>';
}
?>
Can anyone provide some assistance or advise what I might be doing wrong? I've tried everything I can think of and nothing seems to work... any help or suggestions would be much appreciated.
Thanks.
#Bjorn,
You can see here that entering any non-digit char (like a symbol that might go in a telephone number), will invalidate the number field.
<input type="number" id="check">
<button type="button" onclick="console.log(document.getElementById('check').value)">Check</button>
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Good day, I'm looking for assisting on this. On my PHP page, I'm looking to add a simple mathematical question (ex: 5+2) to stop the spam. Any recommendation please? Would be highly appreciated, also feel free if there's way I can improve my code.
Here is my PHP page and form fields:
<div class="col-xs-12 col-md-8">
<?php
// Contact Form
function contact_form() {
if(isset($_POST["name"]) && $_POST["name"] != "")
{
if(!filter_var($_POST["mail"], FILTER_VALIDATE_EMAIL)) {
echo "<div class='error'>The email address is not valid</div>";
return;
}
if($_POST["name"] == "" || $_POST["mail"] == "" || $_POST["message"] == "") {
echo "<div class='error'>Informations are missing</div>";
return;
}
$name = htmlentities($_POST["name"]);
$message = htmlentities($_POST["message"]);
$message = wordwrap($message, 70, "\r\n");
$to = '#hotmail.com';
$subject = 'Message of '.$name.'';
$headers = 'From: ' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$message_final = "Someone sent you a message \nNom : ".$name."\nCourriel : ".$_POST["mail"]."\n\n\n".$message;
if(mail($to, $subject, $message_final, $headers)) {
echo "<div class='success'>Your message was sent. Thank you!</div>";
return;
} else {
echo "<div class='error'>There was an error. You message was not sent</div>";
return;
}
}
}
contact_form();
?>
<form method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter your name" required>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="mail" name="mail" placeholder="Enter your email" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" name="message" class="form-control" rows="3" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Send</button>
</div>
</form>
</div>
Cheers
I actually do something just like what you've described. There are varying ways to implement this, but an easy way is use a function that generates a random math problem, hashes the answer, and inserts the hash into a hidden field. The user submits the form, and you compare the hash of the answer submitted with the hash in the hidden field. You may also want to consider using unique tokens for forms so forms can't POST to your site without getting a token first.
You can try something like this:
function mathQuestion($lo, $hi) {
$a = mt_rand($lo, $hi);
$b = mt_rand($lo, $hi);
$c = $a + $b;
$hash = md5($c);
$q = "$a + $b";
return array($q, $hash);
}
function mathQuestionVerify($c, $hash) {
return (md5($c) === $hash);
}
Then, in your form, something like:
$mathQ = mathQuestion(10, 89);
$mathText = $mathQ[0];
$mathHash = $mathQ[1];
echo "<div><label for='mathquestion'>What is $mathText?</label><input id='mathquestion' name='mathquestion'></div>";
echo "<input type='hidden' name='mathanswer' value='$mathHash'>";
echo "<input type='hidden' name='token' value='$token'>";
The two fields above are the math related ones. The token variable here is a CSRF token in a form I grabbed this from. Actually, this is just a unique form token as I described earlier - I also use CSRF tokens when users are logged in.
In the example above, when the form loads, we add two numbers each of which are between 10 and 89. You can change these to whatever you want. I use a wider range of numbers for less common tasks, like password resets, since that's not something that's done frequently. For a general contact form you should probably keep these numbers small - probably under 50.
Note that md5 is not cryptographically secure. Neither is sha1. I don't actually think mt_rand() is either. Just throwing this out there. I use md5 in this case because we're not dealing with sensitive data and so a plain, fast hashing function works well for my purposes.
I don't use this mechanism as my sole method of validation, but it can certainly slow down malicious attempts. If you want to go further, you could even use a function to rewrite the numeric question into text to make it harder for bots to spam.
For your specific situation, you might try something like this:
<div class="col-xs-12 col-md-8">
<?php
// Contact Form
function contact_form() {
if(isset($_POST["name"]) && $_POST["name"] != "")
{
if(!isSet($_POST['mathanswer'] || !mathQuestionVerify($_POST['mathanswer'], $_POST['mathhash'])) {
echo "<div class='error'>Incorrect answer.</div>";
return;
}
if(!filter_var($_POST["mail"], FILTER_VALIDATE_EMAIL)) {
echo "<div class='error'>The email address is not valid</div>";
return;
}
if($_POST["name"] == "" || $_POST["mail"] == "" || $_POST["message"] == "") {
echo "<div class='error'>Informations are missing</div>";
return;
}
$name = htmlentities($_POST["name"]);
$message = htmlentities($_POST["message"]);
$message = wordwrap($message, 70, "\r\n");
$to = '#hotmail.com';
$subject = 'Message of '.$name.'';
$headers = 'From: ' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$message_final = "Someone sent you a message \nNom : ".$name."\nCourriel : ".$_POST["mail"]."\n\n\n".$message;
if(mail($to, $subject, $message_final, $headers)) {
echo "<div class='success'>Your message was sent. Thank you!</div>";
return;
} else {
echo "<div class='error'>There was an error. You message was not sent</div>";
return;
}
}
}
contact_form();
?>
<form method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter your name" required>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="mail" name="mail" placeholder="Enter your email" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" name="message" class="form-control" rows="3" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Send</button>
</div>
<?php
$mathQ = mathQuestion(5, 15); # ask user to add 2 random numbers between 5 & 15
$mathText = $mathQ[0];
$mathHash = $mathQ[1];
echo "<div><label for='mathquestion'>What is $mathText?</label><input id='mathquestion' name='mathquestion'></div>";
echo "<input type='hidden' name='mathanswer' value='$mathHash'>";
?>
</form>
</div>
I'm working on a simple single page site from a template. The contact from had only name email and message body. I tried adding the number. It shows up on the page, and the line shows up in the email, but the number does not actually come through.
Ive copied and pasted the existing code for one of the other data points and changed the id, type etc. for the phone number.
The page is live on test.wotactical.com
EDIT: Added the javascript code
PHP
<?php
// Put contacting email here
$php_main_email = "ffl#wotactical.com";
$php_sending_email = "contact#wotactical.com";
//Fetching Values from URL
$php_name = $_POST['ajax_name'];
$php_email = $_POST['ajax_email'];
$php_phone = $_POST['ajax_phone'];
$php_message = $_POST['ajax_message'];
//Sanitizing email
$php_email = filter_var($php_email, FILTER_SANITIZE_EMAIL);
//After sanitization Validation is performed
if (filter_var($php_email, FILTER_VALIDATE_EMAIL)) {
$php_subject = "New WOtactical contact form from " . $php_name;
// To send HTML mail, the Content-type header must be set
$php_headers = 'MIME-Version: 1.0' . "\r\n";
$php_headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$php_headers .= 'From:' . $php_sending_email. "\r\n"; // Sender's Email
$php_headers .= 'Cc:' . $php_email. "\r\n"; // Carbon copy to Sender
$php_template = '<div style="padding:50px;">Hello ' . $php_name . ',<br/>'
. 'Thank you for contacting us.<br/><br/>'
. '<strong style="color:#f00a77;">Name:</strong> ' . $php_name . '<br/>'
. '<strong style="color:#f00a77;">Number:</strong> ' . $php_phone . '<br/>'
. '<strong style="color:#f00a77;">Email:</strong> ' . $php_email . '<br/>'
. '<strong style="color:#f00a77;">Message:</strong> ' . $php_message . '<br/><br/>'
. 'This is a Contact Confirmation mail.'
. '<br/>'
. 'We will contact you as soon as possible .</div>';
$php_sendmessage = "<div style=\"background-color:#f5f5f5; color:#333;\">" . $php_template . "</div>";
// message lines should not exceed 70 characters (PHP rule), so wrap it
$php_sendmessage = wordwrap($php_sendmessage, 70);
// Send mail by PHP Mail Function
mail($php_main_email, $php_subject, $php_sendmessage, $php_headers);
echo "";
} else {
echo "<span class='contact_error'>* Invalid email *</span>";
}
?>
HTML
<!-- CONTACT1 -->
<div class="edina_tm_section" id="contact">
<div class="edina_tm_main_title_holder_wrap contact">
<div class="number_wrap">
<span>06</span>
</div>
<div class="title_wrap">
<span>Contact Form</span>
</div>
</div>
<div class="edina_tm_contact_wrap">
<div class="short_info">
<div class="container">
<div class="subtitle">
<p class="wow fadeIn" data-wow-duration="1.2s">Special order, FFL Transfer, consignment or just have questions? We're happy to help.</p>
</div>
</div>
</div>
<div class="main_input_wrap">
<form action="/" method="post" class="contact_form" id="contact_form">
<div class="returnmessage" data-success="Your message has been received, We will contact you soon."></div>
<div class="empty_notice"><span>Please Fill Required Fields</span></div>
<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.2s">
<input id="name" type="text" placeholder="Your Name">
</div>
<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
<input id="email" type="text" placeholder="Your Email">
</div>
<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
<input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
</div>
<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.6s">
<textarea id="message" placeholder="Type of inquiry, and/or details"></textarea>
</div>
<div class="edina_tm_button wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.8s">
<a id="send_message" href="#">Send Message</a>
</div>
</form>
</div>
</div>
</div>
<!-- /CONTACT1 -->
javascript
// -----------------------------------------------------
// ---------------- CONTACT FORM -----------------
// -----------------------------------------------------
function edina_tm_contact_form(){
"use strict";
jQuery(".contact_form #send_message").on('click', function(){
var name = jQuery(".contact_form #name").val();
var email = jQuery(".contact_form #email").val();
var phone = jQuery(".contact_form #phone").val();
var message = jQuery(".contact_form #message").val();
var subject = jQuery(".contact_form #subject").val();
var success = jQuery(".contact_form .returnmessage").data('success');
jQuery(".contact_form .returnmessage").empty(); //To empty previous error/success message.
//checking for blank fields
if(name===''||email===''||phone===''||message===''){
jQuery('div.empty_notice').slideDown(500).delay(2000).slideUp(500);
}
else{
// Returns successful data submission message when the entered information is stored in database.
jQuery.post("modal/contact.php",{ ajax_name: name, ajax_email: email, ajax_phone: phone, ajax_message:message, ajax_subject: subject}, function(data) {
jQuery(".contact_form .returnmessage").append(data);//Append returned message to message paragraph
if(jQuery(".contact_form .returnmessage span.contact_error").length){
jQuery(".contact_form .returnmessage").slideDown(500).delay(2000).slideUp(500);
}else{
jQuery(".contact_form .returnmessage").append("<span class='contact_success'>"+ success +"</span>");
jQuery(".contact_form .returnmessage").slideDown(500).delay(4000).slideUp(500);
}
if(data===""){
jQuery("#contact_form")[0].reset();//To reset form fields on success
}
});
}
return false;
});
}
I'm guessing that if you might remove your regex pattern:
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
here in this element:
<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
<input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
and change it to just:
<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
<input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" required>
and test it, it would likely work. Or you might just test it with a 888-888-8888 number and see if it would work.
I have no real experience with PHP, and so have just pulled bits of code from various answers to help construct a simple PHP contact form. I have spent two days trying to work out why various variations aren't working. I've included my code:
HTML :
<section class="form-section" id="form-section">
<div class="row headline">
<h3>Free Quotation</h3> </div>
<div class="row">
<form action="mailer.php" method="post" name="htmlform" class="contact-form" target="_blank">
<div class="col span-1-of-2">
<div class="row inputs">
<label for="name">Name</label>
<input name="name" placeholder="Your name" required="" type="text"> </div>
<div class="row inputs">
<label for="email">Email</label>
<input name="email" placeholder="Your email" required="" value="" type="email" class="required email"> </div>
<div class="row inputs">
<label for="business_name">Business Name</label>
<input value="" name="business_name" placeholder="Your business name" required="" type="text" class=""> </div>
</div>
<div class="col span-1-of-2 message-box-container">
<label class="text-box-label" for="message">In a few words, what are you looking for?</label>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<div class="row form-messages">
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try again</div>";
}
?> </div>
<div class="col span-2-of-3">
<div class="clear">
<input type="submit" value="Find Out More" name="subscribe" class="button"> </div>
</div>
</form>
</div>
</section>
This is my mailer.php form:
<?php
// Get the form fields, removes html tags and whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$business_name = strip_tags(trim($_POST["business-name"]));
$business_name = str_replace(array("\r","\n"),array(" "," "),$business_name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "chussell#thegreenbuddha.co.uk";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_content .= "Business Name: $business_name \n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=1#form");
?>
When I have this on live preview both success and error messages display with PHP code. I have the file saved as a index.php. And when I submit it opens up the fresh page which is blank.
When I've added the new index.php and mailer.php to my cpanel, my website no longer displays!
Any suggestions or improvements?
Many thanks!
The following
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try gain</div>";
}
?>
Into
<?php
if($_GET['success'] == 1) {
echo '<div class="success">Thank You! We\'ll aim to follow up as soon as possible</div>';
}
if($_GET['success'] == -1) {
echo '<div class="error">Oops something went wrong, please try gain</div>';
}
?>
The following
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Into
if (empty($name) || empty($business_name) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Please change the following also:
$business_name = strip_tags(trim($_POST["business-name"]));
Into
$business_name = strip_tags(trim($_POST["business_name"]));
I have a pretty basic PHP site and I want a simple spam protection to stop the spam submissions.
I've found one that I like which is a basic 4 character input. Easy to read, small space requirements.
But it says to use a validate.php for the submission action.
My current form's action is to call a the mailer.php (<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">) which is actually included on page load (<?php include 'includes/mailer.php'; ?>).
Can I have two 'actions'? If not, how can I implement the use of this captcha?
When I try adding session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
Just after the opening <?php in mailer.php and then }
else
{
die("Wrong Code Entered");
} just before the closing ?>, the whole website just displays "Wrong code entered" on load.
EDIT:
I'm having trouble understanding where I need to place the various parts of the code and how to tweak it so it works with the existing mailer script.
My unmodified index.php basically consists of the following:
<?php
include 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section id="section-home">
<header>
<!-- header content -->
<!-- navigation -->
</header>
</section>
<section class="banner full-width-container">
<div class="container">
<!-- other body content -->
<div id="contact">
<div id="contact-form-message"><?php print $output; ?></div>
<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">
<p><span style="color:#f7403a;">Fill in the form below to have an expert contact you</span></p>
<div class="form-left">
<div class="control-group">
<label for="name" class="assistive control-label">Name:</label>
<div class="controls">
<input type="text" name="name" id="name" value="Your Name" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="email" class="assistive control-label">Email: </label>
<div class="controls">
<input type="text" name="email" id="email" value="Your email address" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-left -->
<div class="form-right">
<div class="control-group">
<label for="subject" class="assistive control-label">Subject: </label>
<div class="controls">
<input type="text" name="subject" id="subject" value="Subject" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="telephone" class="assistive control-label">Telephone number </label>
<div class="controls">
<input type="text" name="telephone" id="telephone" value="Your phone number" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-right -->
<div class="control-group">
<label for="message" class="assistive control-label">Message: </label>
<div class="controls">
<textarea name="message" id="message" class="replace-default required type-textarea full-width" rows="5" cols="20">The type of enquiry (e.g. Motor Accident) and a brief message</textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" id="submit" name="submit" class="btn btn-stacks" value="Send Message"/>
<div id="sending-message"><img src="img/ajax-loader.gif" alt="" /></div>
</div>
</div>
</form>
</div>
</div>
</section>
<footer class="full-width-container" id="footer-section">
<div class="container">
<!-- footer content -->
</div>
</footer>
<!-- ============================================== -->
<script src="js/modernizr-1.7.min.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.flexslider-min.js"></script>
<script src="js/waypoints.min.js"></script>
<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
And my unmodified mailer.php consist of:
<?php
function cleanInput($input){
$input = trim($input);
if(strlen($input)>0){
$input = htmlspecialchars(stripslashes($input));
}
return $input;
}
$name = '';
$email = '';
$subject = '';
$message = '';
$telephone = '';
$output = '';
if ( isset($_POST['submit']) || isset($_GET['ajax']) == 'true'){
//set up for form fields
$name = cleanInput($_POST['name']);
$email = cleanInput($_POST['email']);
$subject = cleanInput($_POST['subject']);
$telephone = cleanInput($_POST['telephone']);
$message = cleanInput($_POST['message']);
$output ='';
$regex = "/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix";
//do some basic validation
if( $name == '' || $name == 'Full Name' ){ $output = '<li class="alert alert-error">Please enter your name.</li>'; }
if ( !preg_match( $regex, $email ) || $email == 'Email address' ) {
$output .= '<li class="alert alert-error">Please check that your email address is valid</li>';
}
if( $subject == '' || $subject == 'Subject' ){ $output .= '<li class="alert alert-error">Please enter a subject</li>'; }
if( $telephone == '' || $telephone == 'Contact number' ){ $output .= '<li class="alert alert-error">Please enter a contact number</li>'; }
if( $message == '' || $message == 'Your Query' ){ $output .= '<li class="alert alert-error">Please enter a message</li>'; }
//if there are errors, add them to the list here
if ( $output!='' ){
$output = '<div class=""><ul class="unstyled">' . $output . '</ul></div>';
}
//if no errors, try to send the form
else {
/*Put the email address to send to here*/
$to = "email1#domain.com.au";
$headers = 'From: noreply#domain.com.au' . "\r\n";
$headers .= 'Cc: '. $email . "\r\n";
$headers .= 'Bcc: email2#domain.com.au' . ', ' . 'email3#domain.com.au' . ', ' . 'email4#otherdomain.com.au' . "\r\n";
$subject = $subject;
$body = "Name: $name\n\n"
. "Email: $email\n\n"
. "Subject: $subject\n\n"
. "Message: $message"
;
$messageOK = ( mail($to, 'Web Enquiry from the landing page for: ' . $subject, $body, $headers ));
//check if the mail was sent or not
if ( $messageOK ){
$output = '<div class="alert alert-success"><p>Thank you for getting in touch. We will be in contact soon.</p></div>';
}
else {
$output = '<div class="alert alert-error"><p>We could not send your message. Please try again.</p></div>';
}
}
//if ajax is being used, output the message
if ( isset($_GET['ajax']) == 'true' ){
print $output;
}
}
?>
Any information that helps me understand what is required to use this captcha code would be greatly appreciated
You could use a random number generated when form is generated, then passing the value using POST AND $_SESSION, and then compare 2 to see if they match. This is for bot protection/spam.
Would you like an example?
EDIT, didn't fully read the question.
What you want to do is to decide whether the page is loaded as POST request, if is not, then display the form, if is, validate $_POST fields and/or send email.
session_start();
$error = null;
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff`
else
{
$error = "invalid captcha image, please try again!";
}
//the rest of your HTML
//after the recaptcha image HTML
echo isset($error)? $error: '';
This will stop the page from dieing because of the failed captcha, and will produe an error message of 'Invalid captcha image' if the capthc was false.
I am updating a client site and the simple contact form that used to work is now broken. It appears that the HTML form sends and receives data from the jQuery file as I get the error messages returned, though it is not passing the data through to the PHP file for sending an email. If I send the data direct from the HTML form to the PHP file, then an email is sent. The error is probably at the end of the jQuery, though my search for how to fix has not revealed an answer. Any ideas on how to make this work?
HTML Form
<form id="rsForm" action="#" onsubmit="return goContact(this);" name="rsForm">
<input id="formNam" type="hidden" name="formNam" value="3" />
<div class="CU_row">
<div class="CU_form_title"><label for="firstName">First Name:</label></div>
<div class="CU_form_entry"><input id="firstName" maxlength="120" size="39" name="first" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="lastName">Last Name:</label></div>
<div class="CU_form_entry"><input id="lastName" maxlength="120" size="39" name="last" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="emailAddress">Email:</label></div>
<div class="CU_form_entry"><input id="emailAddress" maxlength="120" size="39" name="email" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="subjectLine">Subject:</label></div>
<div class="CU_form_entry"><input id="subjectLine" maxlength="120" size="39" name="subject" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="messageCopy">Message:</label></div>
<div class="CU_form_entry"><textarea id="messageCopy" rows="6" cols="30" name="message"></textarea> <span class="redT">*</span></div>
</div>
<div id="CU_reset"><input type="reset" value="Reset" /></div>
<div id="CU_submit"><input type="submit" name="Submit" value="Submit" /></div>
jQuery File
// JavaScript Document
function goContact(theForm){
//Validate the forms and create the array to send.
var frmName = theForm.formNam.value;
//Validate Common elements.
if(theForm.firstName.value.length < 1){
alert("You must supply a First Name");
theForm.firstName.focus();
return false;
}
if(theForm.lastName.value.length < 1){
alert("You must supply a Last Name");
theForm.lastName.focus();
return false;
}
if(theForm.email.value.length < 1){
alert("You must supply an Email");
theForm.email.focus();
return false;
}
if(theForm.subjectLine.value.length < 1){
alert("You must supply a Subject");
theForm.subjectLine.focus();
return false;
}
if(theForm.messageCopy.value.length < 1){
alert("You must supply a Message");
theForm.messageCopy.focus();
return false;
}
sendAjaxReq($(theForm).serialize(true));
return false;
}
function showResult(messageText){
//Show the pop up with the confirmation.
$('msgWindow').innerHTML = messageText;
$('rsForm').reset();
$('frmInter').hide();
}
function sendAjaxReq(formEms){
//Send he ajax request
var rSp = new Ajax.Request("includes/sendContact.php", {
method: 'get',
parameters: formEms,
onComplete: receiveRespon});
}
function receiveRespon(oReq, JSONRsp){
//Receive the response from the ajax request.\
var result = JSONRsp;
if(result){
showResult(result);
}
}
PHP File
<?php
if(isset($_GET['Submit'])){
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: no-reply#sitename.com' . "\r\n";
'X-Mailer: PHP/' . phpversion();
$to = "info#sitename.com";
$subject = "Inquiry from " . $_SERVER['HTTP_HOST'];
$message = "A client has sent a contact us email\n\n";
foreach($_GET AS $field => $value) {
$message .= "field = $field, value = $value \n\n";
}
$mailSent = mail($to, $subject, $message, $headers);
$arr = "Your message has been received.";
header('X-JSON: ('.json_encode($arr).')');
}
?>