I have created a WordPress template which has the capability of sending emails via ajax and the wp_mail function. The everything is okay apart from the wp_mail function which gives a false response and therefore the email is not sent. I have tried researching for a possible solution for almost a week now but no success. Below is my code, hope you can help me figure out where the issue is.
The error displayed is on this line
throw new Exception('Failed to send email. Check AJAX handler
fruu.');
located in the functions.php file.
template functions.php file
wp_enqueue_script('jquery');
function makeBooking() {
try {
if (empty($_POST['start']) || empty($_POST['names']) || empty($_POST['email']) || empty($_POST['bphone']) || empty($_POST['adult']) || empty($_POST['child'])) {
throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.');
}
if (!is_email($_POST['email'])) {
throw new Exception('Kindly enter a valid email.');
}
$e = explode(" - ", $_POST['start']);
$date1 = new DateTime($e['0']);
$date2 = new DateTime($e['1']);
$diff = $date2->diff($date1)->format("%a");
if(($diff < '2') ? $s='': $s='s');
if (($_POST['adult'] < '2') ? $ss = '' : $ss = "s");
if ($_POST['child'] == 'no') {
$cs = "No Children";
} else {
if ($_POST['child'] < '2') {
$cs = "1 Child";
} else {
$cs = $_POST['child'].' Children';
}
}
if ($_POST['req'] == '') {
$req = "";
} else {
$req = " \n\nSpecial Request: ".$_POST['req'];
}
$subject = 'New Booking Request from: '.$_POST['names'];
$headers = 'From: '.$_POST['names'].' <'.$_POST['email'].'>';
$send_to = "booking#mysite.com";
$message = "Booking Duration: ".$diff." day".$s." from ".date("l M dS, Y", strtotime($e['0']))." to ".date("l M dS, Y", strtotime($e['1']))." \n\nBooking Party: ". $_POST['adult'] . " Adult".$ss." and ".$cs.". \n\nContact Number: +" . $_POST['bphone']."".$req;
if (wp_mail($send_to, $subject, $message, $headers)) {
echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.'));
exit;
} else {
throw new Exception('Failed to send email. Check AJAX handler fruu.'); //THIS IS THE ERROR THAT IS RETURNED BY THE SCRIPT
}
} catch (Exception $e) {
echo json_encode(array('status' => 'error', 'message' => $e->getMessage()));
exit;
}
}
add_action("wp_ajax_makeBooking", "makeBooking");
add_action('wp_ajax_nopriv_makeBooking', 'makeBooking');
The Form
<form class="contact modal-form" name="contact" id="booking_form">
<input type="hidden" name="form_send" value="send" />
<input required class="col-lg-12 form-control" name="start" id="start" placeholder="Duration of Stay" type="text">
<input required class="col-lg-12 form-control" name="end" id="end" value="" placeholder="Departure Date" type="text">
<input required class="form-control col-lg-12" name="names" id="names" value="" placeholder="Full Names" type="text">
<input required class="form-control col-lg-12" name="email" id="email" value="" placeholder="Email Address" type="email">
<input required class="form-control col-lg-12" name="bphone" id="bphone" value="" placeholder="Phone Number (e.g 2547xx 123xx4)" type="tel">
<select required style="" class="col-lg-12 form-control" name="adult" id="adult">
<option selected="selected" value="">Adults</option>
<?php
echo '<option value="1">1 Adult</option>';
$i = '2';
while ($i < '11') {
$k = $i;
echo '<option value="'.$k.'">'.$k.' Adults</option>';
$i++;
}
?>
</select>
<select required style="" class="col-lg-12 form-control" name="child" id="child">
<option selected="selected" value="">Children</option>
<?php
echo '<option value="no">No Children</option>';
echo '<option value="1">1 Child</option>';
$i = '2';
while ($i < '11') {
$k = $i;
echo '<option value="'.$k.'">'.$k.' Children</option>';
$i++;
}
?>
</select>
<textarea class="form-control col-lg-12" name="req" id="req" placeholder="Special Request"></textarea>
<input type="hidden" name="action" value="makeBooking" />
<button class="btn btn-success" type="submit" id="sendBooking"><i class="fa fa-spinner fa-pulse fa-fw hide fa-2x" id="sending"></i><span id="text" class=''>Send</span></button>
</form>
jQuery Code and please note I have left out the code with the data validation rules
$('#sendBooking').click(function(e) {
$.ajax({
url:"/wp-admin/admin-ajax.php",
type:'POST',
dataType: 'JSON',
data:$("#booking_form").serialize(),
cache: false,
success: function(data){
show_ok(data);
},
error: function(){
$("#sending").addClass("hide");
$("#text").removeClass("hide");
$("#sendBooking").removeClass("disabled");
$("#msg_not_sent").removeClass("hide");
}
});
e.preventDefault();
});
Thanks in advance.
Make sure all serialize data you are getting in ajax call.if require use PHP unserialize function:
parse_str($_POST["data"], $_POST);
Then change
$send_to = "booking#mysite.com";
to your actual email and check it again.
I discovered the source of my error after weeks of research. So, the issue is based on PHP rather than the code. As it turns out, the from address has to be similar to the domain name, that is, if the domain name is example.com, the from address has to be email#example.com. If the from address is name#email.com, the connection will be closed by the server automatically.
Related
I have a contact form which is passed to a PHP script through ajax. Once the form is processed, The ajax will perform some actions depending on the response received from json_encode() function in the PHP script. The problem is I get the following error message:
parsererror SyntaxError: Unexpected end of JSON input
readyState:4 responseText:"" status:200 statusText:"OK"
When the dataType is text in the ajax call and the PHP script simply echos a text message, then code works fine, but with json, I get the above error.
I have tried header("Content-Type: application/json")and JSON.parse() with no success. I have added charset="UTF-8" in the header and tried encode_utf8() function on the array passed to json_encode too, but nothing seems to work for me.
I am posting the code for the relevant files below. Any help to resolve this problem will be highly appreciated.
contact.php
<form action="" method="post" name="contactForm" id="contactForm">
<div class="form-row">
<div id="contactFormResponse"></div>
<div class="form-col">
<label for="orderNumer">Order Number</label>
<input type="text" name="orderNumber" id="orderNumber" value="<?php echo ($_POST['orderNumber']); ?>" />
</div>
<div class="form-col">
<label for="comment">Comment *</label>
<textarea name="message" id="comment" maxlength="2000" rows="5"><?php echo ($_POST['comment']); ?></textarea>
</div>
<div class="form-col">
<label for="title">Title *</label>
<select name="title" id="title">
<option value="" <?php if ($_POST['title'] == "") {echo "selected='selected'";} ?>>Select a title...</option>
<option value="ms" <?php if ($_POST['title'] =="ms") {echo "selected='selected'";} ?>>Ms</option>
<option value="miss" <?php if ($_POST['title'] == "miss") {echo "selected='selected'";} ?>>Miss</option>
<option value="mrs" <?php if ($_POST['title'] == "mrs") {echo "selected='selected'";} ?>>Mrs</option>
<option value="mr" <?php if ($_POST['title'] == "mr") {echo "selected='selected'";} ?>>Mr</option>
<option value="other" <?php if ($_POST['title'] == "other") {echo "selected='selected'";} ?>>Other</option>
</select>
</div>
<div class="form-col">
<label for="firstName">First Name *</label>
<input type="text" name="firstName" id="firstName" value="<?php echo ($_POST['firstName']); ?>" />
</div>
<div class="form-col">
<label for="surname">Surname *</label>
<input type="text" name="surname" id="surname" value="<?php echo ($_POST['surname']); ?>" />
</div>
<div class="form-col">
<label for="email">Email Address *</label>
<input type="text" name="email" id="email" value="<?php echo ($_POST['email']); ?>" />
</div>
<div class="form-col">
<input type="submit" name="submitContactForm" id="submitContactForm" value="Submit" class="btn" />
</div>
</div>
</form>
jsCode.js
// process contact form
$("#contactForm").submit(function(e) {
e.preventDefault();
// some jQuery validation goes here...
$.ajax({
type:"POST",
url: "functions.php",
dataType: "json",
data: new FormData(this),
//data: $('form').serialize(),
processData: false,
contentType: false,
success:function(response) {
if(response.status === "OK") {
$("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$("#contactForm")[0].reset();
$(window).scrollTop(0);
} else if (response.status === "error") {
$("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$(window).scrollTop(0);
}
},
error:function(jqXHR, textStatus, errorThrown) {
console.log("JQuery failed: " + textStatus + " with error thrown: " + errorThrown);
console.log(jqXHR);
}
});
});
functions.php
// send email
function sendMessage() {
if (isset($_POST["submitContactForm"])) {
if (!$_POST["comment"]) {
$error .= "<br />Comment is required.";
}
if (!$_POST["firstName"]) {
$error .= "<br />First name is required.";
}
// validation for other form fields goes here...
if ($error) {
echo json_encode(array("status" => "error", "message" => "There were error(s)in your form: " . $error));
} else {
$to = "email#domain.com";
$subject = "Message from the website";
$order_number = $_POST["orderNumber"];
$comment = $_POST["comment"];
$title = $_POST["title"];
$first_name = $_POST["firstName"];
$surname = $_POST["surname"];
$email_address = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$headers = "From: " . $title . " " . $first_name . " " . $surname . " <" . $email_address . " >";
$message = "Order Number: " . $order_number . "/r/n" . "Topic: " . $topic . "/r/n" . "Comment: " . $comment;
$result = mail($to, $subject, $message, $headers);
if (!$result) {
echo json_encode(array("status" => "error", "message" => "Message failed."));
} else {
echo json_encode(array("status" => "OK", "message" => "Message sent."));
}
}
}
}
you are not parsing the json response in your success function,you need to use $.parseJSON(response) like below
success:function(res) {
var response=$.parseJSON(res);
if(response.status === "OK") {
$("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$("#contactForm")[0].reset();
$(window).scrollTop(0);
} else if (response.status === "error") {
$("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$(window).scrollTop(0);
}
},
I'm new to the CakePhp framework and currently i'm testing out a project. Issue i have is, i can populate the dropdown option but when i want to select an option it won't get saved on the database. Did i miss something?
Using this code i can populate the drop down - bookings.js
$("#contact_submit").click(function () {
var name = $("#name").val();
var contact_email = $("#contact_email").val();
var subject = $("#subject").val();
var message = $("#txtmessage").val();
var service = $("#sel1").val();
console.log(name+contact_email+subject+message+service);
$.post("/inquiries/inquiry", //Required URL of the page on server
{// Data Sending With Request To Server
name: name,
email: contact_email,
subject: subject,
txt: message,
service_id: service,
},
function (response) { // Required Callback Function
if (jQuery.parseJSON(response).status == 'success') {
if ($("#available").hasClass("hide")) {
$("#available").removeClass("hide");
}
if (!$("#available").hasClass("hide")) {
$("#notavailable").addClass("hide");
}
}else{
if ($("#notavailable").hasClass("hide")) {
$("#notavailable").removeClass("hide");
}
if (!$("#available").hasClass("hide")) {
$("#available").addClass("hide");
}
}
});
});
InquriesController.php
public function inquiry()
{
$inquiry = $this->Inquiries->newEntity();
if ($this->request->is('post')) {
$emailaddress = $this->request->data['email'];
$subject = $this->request->data['subject'];
$txt = $this->request->data['txt'];
$services = $this->request->data['service_id'];
$message = "this is a message";
$inquiry = $this->Inquiries->patchEntity($inquiry, $this->request->data);
if ($this->Inquiries->save($inquiry)) {
$email = new Email('default');
$email->from(['myemail#gmail.com' => 'Testing Hotel'])
->to($emailaddress)
->subject('Inquiry Mail')
->emailFormat('html')
->send($message);
echo json_encode(['status' => 'success']);
exit;
} else {
echo json_encode(['status' => 'failed']);
exit;
}
}
}
HTML CODE SNIPPET
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" name="contact_email" id="contact_email" class="form-control" placeholder="Email *">
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="subject" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<input class="form-control" name="txtmessage" id="txtmessage" rows="8" placeholder="Messages goes here.."></input>
<div class="form-group">
<select class="form-control" id="sel1">
<option>Select a service</option>
<?php
if (!empty($ServicesInfo)) {
foreach ($ServicesInfo as $Services):
?>
<option value="<?= h($Services->name)?>"><?= h($Services->name)?></option>
<?php endforeach; } ?>
</select>
</div>
As i told you, your int field in the table cannot save the varchar of service name. So, you need to send the service id as value from the select option. Like so :
<option value="<?= h($Services->id)?>"><?= h($Services->name)?></option>
I am having a strange issue where I was able to submit files and successfully upload them, now that I have added this bit of jQuery within the head of the webpage, it doesn't seem to work anymore:
I tested once again without the jQuery and it works perfectly fine, my jQuery is messing with it somewhere. Anyway I can accomplish the same objective, differently?
Jquery:
$(document).ready(function() {
var options = $('select[name=itemType]');
var optionVal = options.val();
var filer = $('input[name=itemFile');
var filerVal = $('input[name=itemFile]').val();
options.change(function() {
optionVal = $(this).val();
if(optionVal == 1 || optionVal == 3) {
$('input[name=itemContact]').removeAttr('disabled');
$('input[name=itemContact]').attr('required','true');
} else {
$('input[name=itemContact]').attr('disabled','true');
$('input[name=itemContact]').removeAttr('required');
};
if(optionVal != 5) {
$('input[name=itemFile]').removeAttr('disabled');
$('span.inputFile').css("display","block");
} else {
$('input[name=itemFile]').attr('disabled','true');
$('span.inputFile').css("display","none");
};
});
filer.change(function() {
filerVal = $(this).val();
$(this).parent().text(filerVal);
});
});
HTML Form:
Note: $sectionName is defined earlier throughout the webpage, and does work.
<form class="col-12" method="post" action="./action.php?upload" enctype="multipart/form-data">
<p class="head">Upload to <i><?php echo $sectionName; ?></i></p>
<div class="con">
<input name="sectionID" type="hidden" value="<?php echo $section; ?>" required />
<select name="itemType" required>
<option selected disabled>Select an Item Type</option>
<option value="1">Downloadable, Contact</option>
<option value="2">Downloadable</option>
<option value="3">Installable, Contact</option>
<option value="4">Installable</option>
<option value="5">Browsable</option>
</select>
<span class="inputFile" style="display:none;">
Select a File
<input name="itemFile" type="file" required />
</span>
<input name="itemName" type="text" placeholder="Enter Item Name" required />
<input name="itemContact" type="email" placeholder="Enter Contact Email Address" disabled />
<button type="submit">Submit</button>
</div>
</form>
action.php?upload:
$fileDir = "./uploads/";
$fileName = preg_replace("/[^A-Z0-9._-]/i", "_", $_FILES['itemFile']["name"]);
$itemDir = $fileDir. $fileName;
$sectionID = $_POST['sectionID'];
$itemName = $_POST['itemName'];
$itemType = $_POST['itemType'];
$itemContact = $_POST['itemContact'];
if (file_exists($itemDir)) {
echo '<p class="alert">Sorry, file already exists</p>';
} else {
if (move_uploaded_file($_FILES["itemFile"]["tmp_name"], $itemDir)) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if($createItem = $con->prepare("INSERT INTO items(sectionID,itemName,itemType,itemDir) VALUES(?,?,?,?)")) {
$createItem->bind_param("isis", $sectionID,$itemName,$itemType,$itemDir);
if($createItem->execute()) {
$itemID = $createItem->insert_id;
if($itemType == 1 || $itemType == 3) {
if($createContact = $con->prepare("INSERT INTO contacts(itemID,itemContact) VALUES(?,?)")) {
$createContact->bind_param("is", $itemID,$itemContact);
if($createContact->execute()) {
echo '<p class="alert">Item Created</p>';
} else {
echo "<p class=alert'>Execute failed: [createContact] (" . $createContact->errno . ") " . $createContact->error. '</p>';
};
} else {
echo '<p class="alert">Item Created</p>';
};
$createContact->close();
};
};
};
$createItem->close();
};
};
Rather than uploading the file, or storing it in $_FILES it doesn't even get passed to action.php. I have checked $_POST and $_FILES, it doesn't show up in either, whereas before it did.
Note: This is an internal website on one of my web servers, so it doesn't matter if it is vulnerable to SQL Injection.
Selector is not valid at this line
var filer = $('input[name=itemFile');
var filer = $('input[name=itemFile ] ');
I've my own custom contact form wordpress plugin, in which I'm unable to reset the form fields after the user submits the form.
When the user fills up all the fields and submits, success message will be shown, and after that I need the form to reset all the fields. At present it shows the values entered by the user before submission.
Any help is greatly appreciated. Thanks in advance. Here is my code.
<?php
/*
Plugin Name: Custom Contact Form
Plugin URI:
Description: <code>[contact email="your#email.address"]</code>
Version: 1.0
Author:
Author URI:
*/
// function to get the IP address of the user
function tw_get_the_ip() {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
return $_SERVER["HTTP_CLIENT_IP"];
}
else {
return $_SERVER["REMOTE_ADDR"];
}
}
// the shortcode
function tw_contact_form_sc($atts) {
extract(shortcode_atts(array(
"email" => get_bloginfo('admin_email'),
"subject" => '',
"label_name" => 'Your Name',
"label_email" => 'Your E-mail Address',
"label_subject" => 'Subject',
"label_message" => 'Your Message',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks for your e-mail! We\'ll get back to you as soon as we can.'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("your_name", "email", "message", "subject");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "[" . get_bloginfo('name') . "] " . $form_data['subject'];
$email_message = $form_data['message'] . "\n\nIP: " . tw_get_the_ip();
$headers = "From: ".$form_data['your_name']." <".$form_data['email'].">\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
wp_mail($email, $email_subject, $email_message, $headers);
$result = $success;
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" action="'.get_permalink().'">
<div>
<label for="cf_name">'.$label_name.':</label>
<input type="text" name="your_name" id="cf_name" size="50" maxlength="50" value="'.$form_data['your_name'].'" />
</div>
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" />
</div>
<div>
<label for="cf_subject">'.$label_subject.':</label>
<input type="text" name="subject" id="cf_subject" size="50" maxlength="50" value="'.$subject.$form_data['subject'].'" />
</div>
<div>
<label for="cf_message">'.$label_message.':</label>
<textarea name="message" id="cf_message" cols="50" rows="15">'.$form_data['message'].'</textarea>
</div>
<div>
<input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info.$email_form;
} else {
return $info.$email_form;
}
} add_shortcode('contact', 'tw_contact_form_sc');
?>
In this instance you can just manually assign your values on $sent == true:
// Presumably if the email is sent, you want blank values instead
// of populated ones.
if($sent == true) {
$form_data['your_name'] = "";
$form_data['email'] = "";
$form_data['subject'] = "";
$form_data['message'] = "";
}
$email_form = '<form class="contact-form" method="post" action="'.get_permalink().'">
<div>
<label for="cf_name">'.$label_name.':</label>
<input type="text" name="your_name" id="cf_name" size="50" maxlength="50" value="'.$form_data['your_name'].'" />
</div>
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" />
</div>
<div>
<label for="cf_subject">'.$label_subject.':</label>
<input type="text" name="subject" id="cf_subject" size="50" maxlength="50" value="'.$subject.$form_data['subject'].'" />
</div>
<div>
<label for="cf_message">'.$label_message.':</label>
<textarea name="message" id="cf_message" cols="50" rows="15">'.$form_data['message'].'</textarea>
</div>
<div>
<input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
There are lots of ways to do this, but without doing much in the way of modifying what you have, this is probably the quickest.
if you are using Ajax/Json for submit form, then after submit form put a simple code in ajax/json
$('form').reset();
also you set a custom class for all input fields just ex. class name :clear
then use
$('.class').val('');
and simple answer is this:
<input type="submit" onClick="this.form.reset()" />
Please bear with me as I am a graphic designer with some coding knowledge, but not near as much as a developer. And after many hours of tinkering and asking Google, I've decided to ask y'all directly!
I've been working on building a contact form for my website. So far so good, except for one thing. I would like to add a simple spam prevention field.
I've added a field "spamcheck" with the question 6+2=? but I do not know how to code the PHP to require that the value specifically be 8. As long as the other fields are correctly filled out, the form will submit regardless of the number entered here despite any attempt to mess with the code (thus why you will see my $spamcheck variable but the current coding only requires that it have a value like the rest of the fields).
I have included the PHP, the validation the PHP calls to, and the form. Apologies if the form has some excess code; I have tried many different versions of PHP form tutorials to no avail.
And of course, thank you very much for your help! :)
Here is the PHP code I have placed directly in the web page:
<?php
define("EMAIL", "email#gmail.com");
if(isset($_POST['submit'])) {
include('validate.class.php');
//assign post data to variables
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$budget = trim($_POST['budget']);
$deadline = trim($_POST['deadline']);
$message = trim($_POST['message']);
$spamcheck = trim($_POST['spamcheck']);
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 1, 50);
$v->validateEmail($email, "email");
$v->validateStr($budget, "budget");
$v->validateStr($deadline, "deadline");
$v->validateStr($message, "message", 1, 1000);
$v->validateStr($spamcheck, "spamcheck");
if(!$v->hasErrors()) {
$from = "website.com"; //Site name
// Change this to your email address you want to form sent to
$to = "email#gmail.com";
$subject = "Hello! Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Budget: " . $budget ."
Deadline: " . $deadline ."
Message: " . $message ."";
mail($to,$subject,$message,$from);
//grab the current url, append ?sent=yes to it and then redirect to that url
$url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header('Location: '.$url."?sent=yes");
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
$nameErr = $v->getError("name");
$emailErr = $v->getError("email");
$budgetErr = $v->getError("budget");
$deadlineErr = $v->getError("deadline");
$messageErr = $v->getError("message");
$spamcheckErr = $v->getError("spamcheck");
}//end error check
}// end isset
?>
This is the validate.class.php which it calls to:
<?php
class validate {
public $errors = array();
public function validateStr($postVal, $postName, $min = 1, $max = 1000) {
if(strlen($postVal) < intval($min)) {
$this->setError($postName, ucfirst($postName)." is required.");
} else if(strlen($postVal) > intval($max)) {
$this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
}
}// end validateStr
public function validateEmail($emailVal, $emailName) {
if(strlen($emailVal) <= 0) {
$this->setError($emailName, "Please enter an Email Address");
} else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
$this->setError($emailName, "Please enter a Valid Email Address");
}
}// end validateEmail
private function setError($element, $message) {
$this->errors[$element] = $message;
}// end logError
public function getError($elementName) {
if($this->errors[$elementName]) {
return $this->errors[$elementName];
} else {
return false;
}
}// end getError
public function displayErrors() {
$errorsList = "<ul class=\"errors\">\n";
foreach($this->errors as $value) {
$errorsList .= "<li>". $value . "</li>\n";
}
$errorsList .= "</ul>\n";
return $errorsList;
}// end displayErrors
public function hasErrors() {
if(count($this->errors) > 0) {
return true;
} else {
return false;
}
}// end hasErrors
public function errorNumMessage() {
if(count($this->errors) > 1) {
$message = "There was an error sending your message!\n";
} else {
$message = "There was an error sending your message!\n";
}
return $message;
}// end hasErrors
}// end class
?>
And here is the form html/php:
<span class="message"><?php echo $message_text; ?></span>
<?php if(isset($_GET['sent'])): ?><h2>Your message has been sent</h2><?php endif; ?>
<form role="form" method="post" action="webpage.php#contact">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" value="<?php echo htmlentities($name); ?>" placeholder="Full Name" required>
<label for="exampleInputName"><i class="icon-tag"></i></label>
<span class="errors"><?php echo $nameErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" id="email" value="<?php echo htmlentities($email); ?>" placeholder="Email" required>
<label for="exampleInputEmail1"><i class="icon-inbox"></i></label>
<span class="errors"><?php echo $emailErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="text" name="budget" class="form-control" id="budget" value="<?php echo htmlentities($budget); ?>" placeholder="Budget" required>
<label for="exampleInputBudget1"><i class="icon-usd"></i></label>
<span class="errors"><?php echo $budgetErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="text" name="deadline" class="form-control" id="deadline" value="<?php echo htmlentities($deadline); ?>" placeholder="Deadline" required>
<label for="exampleInputDeadline"><i class="icon-calendar"></i></label>
<span class="errors"><?php echo $deadlineErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group textarea">
<textarea rows="6" name="message" class="form-control" id="message" value="<?php echo htmlentities($message); ?>" placeholder="Write Message" required></textarea>
<label for="exampleInputMessage"><i class="icon-pencil"></i></label>
<span class="errors"><?php echo $messageErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="text" name="spamcheck" class="form-control" id="spamcheck" value="<?php echo htmlentities($spamcheck); ?>" placeholder="Spam check: 6+2=?" required>
<label for="exampleInputSpamCheck"><i class="icon-lock"></i></label>
<span class="errors"><?php echo $spamcheckErr; ?></span>
<div class="clearfix"></div>
</div>
<button type="submit" id="submit" name="submit" value="submit" class="btn btn-large">Send Message</button>
</form>
In the PHP script where you generate the form, you should save the correct answer to the question in a $_SESSION variable.
Then, in the PHP script that receives this form data, you should verify that what was submitted for that question matches the right answer in the $_SESSION variable.
There are a bunch of tutorials on how to use sessions in PHP.
Basically, it comes down to:
form.php
<?php
session_start();
$_SESSION['captcha_right_answer'] = somehow_generate_this();
?>
handler.php
<?php
session_start();
if ($_INPUT['captcha_answer'] != $_SESSION['captcha_right_answer']) {
// Show "bad captcha" message, re-show form, whatever
}
else {
// Captcha good - go on with life
}
?>
Check this out as an alternative to a captcha. Then you could use your existing class to validate the field. Say your hidden field has a name "fakeField" You could validate it with your validateSTR method via..
$v->validateStr($fakeField, "fakeField",0,0);
Since your str check is checking > and < instead of >= and <= this will return true when the length is exactly 0. This might be an easier solution for someone with little code knowledge to integrate.
Alternatively, if you're stuck on using a captcha of sort, and you know what you expect the value to be, you could add a method to check against the value you're expecting.
The method:
public function validateCaptcha( $value,$name, $expectedValue) {
if(trim($value) != $expectedValue) {
$this->setError($name, "Captcha Incorrect");
}
}
then change the line of code
$v->validateStr($spamcheck, "spamcheck");
to
$v->validateCaptcha($spamcheck, "spamcheck", '6');
This isn't the best solution since there are so many powerful captchas out therebut it's easy to use.
Another simple method is to capture the time the page loads and compare it to the time the form was submitted. If the difference was too short, exit the page. spambots are quick; people are slow. Spambots may figure out various fields - even do math - but they are never going to wait around for more than a few seconds.
It takes only two lines, one in the form:
<input name="timeloaded" type="hidden" value="<?php echo time();?>" />
and one in the form processing code:
if(!(is_numeric($_POST['timeloaded'])) || time()-$_POST['timeloaded']<30) {header("Location: index.php"); exit;}
This one is for a form that no human can fill out in less than 30 seconds. Change that for the length of form you use.