I came across a problem with PHP form submission. I'm not able to read the captcha filed value in form submission. Here is the code
HTML
<div class="container">
<h2 class="centertitle">Contact Us</h2>
<div id="message"></div>
<form method="post" action="php/contact.php" name="contactform" id="contactform">
<div class="row">
<div class="col-sm-3">
<input type="text" name="name" placeholder="Name" id="name" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="email" placeholder="Email" id="email" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="phone" placeholder="Phone" id="phone" class="form-control" />
</div>
<div class="col-sm-3">
<div id="captcha">
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<input type="submit" name="send" value="Submit" id="submit" class="sbtn" />
</div>
</div>
</form>
</div><!-- /.container -->
Js Validation
$(document).ready(function() {
//Form Validation
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
//.after('<img src="images/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
subject: $('#subject').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
});
Contact.PHP
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Attention! Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Attention! Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) === $_SESSION["security_number"]) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "contact#sreejesh.in";
$e_subject = 'Form Submission.';
$e_body = "You have a new Form Submission." . PHP_EOL . PHP_EOL;
$e_content = "Name: $name,\rPhone: $phone,\rEmail: $email" . PHP_EOL . PHP_EOL;
$e_reply = "";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h4>Email Sent Successfully.</h4>";
echo "<p>Thank you <strong>$name</strong>, for your interest We will contact you shortly.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
For some reason I'm NOT getting value of $captcha
It returns an error says**
Currently the form get submitted without validation.
For Captcha image I use this code -
Captcha Code(IMAGE.PHP)
<?php
session_start();
$img=imagecreatefromjpeg("texture.jpg");
$security_number = empty($_SESSION['security_number']) ? 'error' : $_SESSION['security_number'];
$image_text=$security_number;
$red=rand(100,255);
$green=rand(100,255);
$blue=rand(100,255);
$text_color=imagecolorallocate($img,255-$red,255-$green,255-$blue);
$text=imagettftext($img,16,rand(-10,10),rand(10,30),rand(25,35),$text_color,"fonts/courbd.ttf",$image_text);
header("Content-type:image/jpeg");
header("Content-Disposition:inline ; filename=secure.jpg");
imagejpeg($img);
?>
I'm a beginer in PHP & I'm sitting with this code for the last few hours. PLs help.
Here is a live URL - http://aisther.com/projects/sri/
Do not echo your session variable is it being created by your image.php script and exposing it to the user makes the captcha pointless.
HTML
<form action="contact.php" method="post">
<div id="captcha">
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
</div>
</form>
PHP
session_start();
if($_POST'verify'] == $_SESSION["security_number"]) {
echo 'captcha matched';
} else {
echo 'bad captcha';
}
If you want to use $_POST to read the form data, the form tag needs to look like
<form action='contact.php' method='post'>
Issue solved after adding session_start(); in contact.php
final code(contact.php)
<?php
session_start();
*********************************************************
$verify = $_POST['verify'];
$captcha = $_SESSION["security_number"];
*********************************************************
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) != trim($captcha)) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
*********************************************************
?>
Related
For my WordPress (v5.5.1) I am using Bootstrap and built a Custom Contact Form in Bootstrap Modal with below HTML (followed this tutorial: https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/).
<form id="contact-form" action="<?php echo get_site_url(); ?>" method="post">
<div class="modal-body">
<?php echo $response; ?>
<div class="form-group">
<input class="form-control my-2" type="text" name="message_name" size="50" placeholder="Your full name" value="<?php echo esc_attr($_POST['message_name']); ?>">
<input class="form-control my-2" type="email" name="message_email" size="50" placeholder="Email address" value="<?php echo esc_attr($_POST['message_email']); ?>">
<input class="form-control my-2" type="tel" name="message_tel" size="50" placeholder="Country code, Phone number" value="<?php echo esc_attr($_POST['message_tel']); ?>">
<textarea class="form-control my-2" name="message_text" rows="2" placeholder="Your message" value="<?php echo esc_attr($_POST['message_text']); ?>"></textarea>
<input class="form-control my-2" type="text" name="message_human" placeholder="Human check: Enter 2">
<input type="hidden" name="message_url" value="<?php the_permalink(); ?>">
<input type="hidden" name="message_page" value="<?php the_title(); ?>">
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="submitted" value="1">
<button type="submit" value="Submit" class="btn btn-search form-control">Send Enquiry</button>
</div>
Below the function to validate the Forms & show responses while Form submission:
function validateform() {
//response generation function
$response = "";
//function to generate response
function contact_g_form_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
}
//response messages
$not_human = "Enter current year in numbers.";
$missing_content = "Missing something.";
$email_invalid = "Check your Email address.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! We got your enquiry.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$fromEmail = $name . '<' . $email . '>';
$tel = $_POST['message_tel'];
$text = $_POST['message_text'];
$url = $_POST['message_url'];
$page = $_POST['message_page'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = '[General Enquiry] ' . $name . ' | Phone Number:' . $tel;
$headers = 'From: ' . $fromEmail . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$message = '<html><body><h1>New general enquiry from ' . $name . '!</h1>'
. '<p>Email: ' . $email . '</p>'
. '<p>Phone Number: ' . $tel . '</P>'
. '<p>Inquiry: ' . $text . '</P>'
. '<p>From page: <b>' . $page . '</b></P>'
. '<p>Page URL: ' . $url . '</p>'
. '</body></html>';
if (!$human == 0) {
if ($human != 2) {
contact_g_form_response("error", $not_human); //not human!
} else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
contact_g_form_response("error", $email_invalid);
} else { //email is valid
//validate presence of name, phone number
if (empty($name) || empty($tel)) {
contact_g_form_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to, $subject, $message, implode("\r\n", $headers)); //mail to admin - striptags removing formatting
// $sent2 = wp_mail($email, $subject, $body, $headers); //mail to visitor
// if ($sent || $sent2) {
if ($sent) {
contact_g_form_response("success", $message_sent); //message sent!
} else {
contact_g_form_response("error", $message_unsent); //message wasn't sent
}
}
}
}
} else if ($_POST['submitted']) {
contact_g_form_response("error", $missing_content);
}
}
In the earlier versions of WordPress the email was being sent without validation, with v5.5.1 upgrade, the Modal is closing without any validation and the email is also not being sent.
You Just Need To replace this:
<form id="contact-form" action="<?php echo get_site_url();?>" method="post">
With This:
<form id="contact-form" method="post">
Because You are displaying the error on the same page but on click of the submit button the action is taking you to a specific url and that's the reason the validations are not shown.
And This:
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
With This also:
if ($type == "success") {
$response = $message;
echo $response;
} else {
$response = $message;
echo $response;
}
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I was working on my own vCard/resume website.
But I am having some trouble with my .php file and contact form.
I tried to debug it but I had no success.
Here is my form in html
<!-- form -->
<form name="contactForm" id="contactForm" method="post" action="inc/sendEmail.php">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required>
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required>
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="Message" rows="10" cols="50" required></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">
Sending...
</div>
<div class="s-loader">
<div class="bounce1">
</div>
<div class="bounce2">
</div>
<div class="bounce3">
</div>
</div>
</div>
</div>
</fieldset>
</form>
<!-- Form End -->
And my php file
<?php
// Replace this with your own email address
$siteOwnersEmail = 'someone#example.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Can someone tell me what I am doing wrong here, because it isn't sending any emails.
Please try this
<?php
$message ="";
if(isset($_POST)){
mail(to,subject,message,headers,parameters);
}
?>
You have to declare type of button type="submit" OR type="button"
in this case work with form so you have to add type="submit"
and check user click button or direct access of file you can check !empty($_POST) with if
// Change in your HTML
<button class="submitform">Submit</button>
// to
<button type="submit" class="submitform">Submit</button>
//Change in your PHP
if($_POST)
// to
if(!empty($_POST))
I'm getting the following error for a contact form
Notice: Undefined variable: sumNums in C:\xampp\htdocs\tedx\contact.php on line 45
I've already tried 'isseting' it.
Below is my HTML markup regarding this.
<form class="contact-form" method="post" action="contact.php" name="contactform" id="contactform">
<div class="row">
<div class="large-6 columns">
<div class="row">
<div class="large-12 columns">
<label>Name<small class="astrix">*</small>
<input type="text" id="name" name="name" />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Email<small class="astrix">*</small>
<input type="text" id="email" name="email" />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Subject<small class="astrix">*</small>
<input type="text" id="subject" name="subject" />
</label>
</div>
</div>
</div>
<div class="large-6 columns">
<label>Message<small class="astrix">*</small>
<textarea cols="30" rows="8" id="comments" name="comments"></textarea>
</label>
</div>
</div>
<div class="row captcha">
<div class="large-6 columns">
<label for="captcha-code">Enter the following sum<small class="astrix">*</small><br>
<span class="captcha-chars" name="captcha-chars">
<span name="num1" id="num1">
<?php
$num1 = rand(1, 9);
echo $num1;
?>
</span>
+
<span name="num2" id="num2">
<?php
$num2 = rand(1, 9);
echo $num2;
?>
</span>
<?php $sumNums = $num1+$num2; ?>
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
</span>
<input type="text" id="verify" name="verify">
</label>
</div>
<div class="large-6 columns mt-25">
<button type="submit" id="submit" class="submit"><img src="img/btn-submit.png" alt=""></button>
</div>
</div>
</form>
And the PHP:
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$subject = trim($_POST['subject']);
$comments = trim(strip_tags($_POST['comments'], '<p><b><a><i>'));
$verify = trim($_POST['verify']);
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
if(trim($name) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter your name.</div>';
exit();
} else if(!ctype_alpha($name)) {
echo '<div class="error_message"><i class="fi-x"></i>Your name should\'t contain digits or speicla characters</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter your email ID</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message"><i class="fi-x"></i>You have entered an invalid email ID, try again.</div>';
exit();
}
if(trim($subject) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter a subject.</div>';
exit();
} else if(!ctype_alpha($subject)) {
echo '<div class="error_message"><i class="fi-x"></i>Your subject should\'t contain digits or speicla characters</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter a message.</div>';
exit();
} else if(!isset($verify) || trim($verify) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter the verification number.</div>';
exit();
} else if(trim($verify) != $sumNums) {
echo '<div class="error_message"><i class="fi-x"></i>The verification number you entered is incorrect.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#themeforest.net";
$address = "njshah#aixsol.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email.";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<div id='success_page' class='success_message'>";
echo "<p><i class='fi-check'></i>Message sent successfully.";
echo "Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
} else {
echo 'ERROR!';
}
How do I solve this issue?
You need to answer yourself a question about the line below. Will the $sumNums be defined if the POST isn't submitted?
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
In form you gave wrong name for sunNums it should be sumNums
So, Replace
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
with
<input type="hidden" value="<?php echo $sumNums; ?>" name="sumNums" id="sumNums">
I have just changed the name attribute.
Your input has
name="sunNums"
and you are using
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
in HTML name is sunNums
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
but in PHP you use sumNums
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
Problem is this:
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
$sumNums variable is not defined. There is no such index in $_POST.
You can initialize the value
$sumNums = '';
before
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
Otherwise, you can also replace
} else if(trim($verify) != $sumNums) {
by
} else if(isset($sumNums) && trim($verify) != $sumNums) {
I hope it will help you :)
REPLACE:
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
TO
<input type="hidden" value="<?php echo $sumNums; ?>" name="sumNums" id="sumNums">
I'm not very familiar with PHP. In the past I have been able to read and fix small problems using PHP but this one is giving me quite lot of trouble.
I have a form with two entry boxes, one for email and one for message.
Now, Im trying to add another box to the form to verify human access for anti-spam purposes.
This is the code which I can't make the verification process go through.
//create ramdom numbers
<?php
$num1 = rand(0,9);
$num2 = rand(0,9);
?>
<?php
$error = '';
$email = '';
$comments = '';
$verify = '';
if(isset($_POST['contactus'])) {
$email = $_POST['email'];
$comments = $_POST['comments'];
$app = $_SERVER["REQUEST_URI"];;
if(trim($comments) == '') {
$error = '<div class="error_message">Attention! Please enter your message.</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Attention! Please enter a valid email address.</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
}
//This is where Im having problem. From this point the form doesn't go on.
if(trim($verify) == '') {
error( '<div class="error_message">Attention! Please enter the verification number.</div>');
} else if(trim($verify) != $verify_result) {
error( '<div class="error_message">Attention! The number you entered is incorrect.</div>');
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "info#myaddress.com";
$e_subject = 'You\'ve been contacted from an app web page ' . $name . '.';
$e_body = "You have been contacted using the app comments box on the above app web page, their additional message is as follows.\r\n\n";
$e_content = "\"$comments\"\r\n\n";
$e_reply = "$name $email";
$msg = $e_body . $e_content . $e_reply;
mail($address, $e_subject, $msg, $app, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
// Email has sent successfully, echo a success page.
echo "<div id='success_page_apps'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you, your message has been submitted to us.</p>";
echo "</div>";
echo '<input type="button" value="Send Another" onClick="history.go(-1); return (true); ">';
}
}
if(!isset($_POST['contactus']) || $error != '') {
<?php echo $error; ?>
<fieldset id="contact_apps">
<form method="post" action="#ContactForm">
<label for="email" accesskey="E"><span class="required"></span> Email</label>
<input name="email" type="text" id="email" size="33" value="<?php echo$email;?>"/>
<textarea name="comments" cols="50" rows="15" id="comments"><?php echo$comments;?></textarea>
//This is the 'Are you human?' message
<p><span class="required">*</span> Are you human?</p>
<label class="numbersq" for='verify' accesskey='V'><?php echo $num1; ?> + <?php echo $num2; ?> =</label>
<input class="numbersa" name="verify" type="text" id="verify" size="4" value=""/>
<input name="verify_result" type="hidden" size="4" value="<?php echo $num1+$num2; ?>" /><br />
<input name="contactus" type="submit" class="send" id="contactus" >
</form>
</fieldset>
}
?>
Please note the 'Are you human' message and the conditionals I have in the script which is where I think I'm doing something wrong.
You've forgotten to pull the verify values from the form ... and you have a few other simple errors in there too which I've addressed.
//create ramdom numbers
<?php
$num1 = rand(0,9);
$num2 = rand(0,9);
?>
<?php
$error = '';
$email = '';
$comments = '';
$verify = '';
if(isset($_POST['contactus'])) {
$email = $_POST['email'];
$comments = $_POST['comments'];
$app = $_SERVER["REQUEST_URI"];;
if(trim($comments) == '') {
$error = '<div class="error_message">Attention! Please enter your message.
</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Attention! Please enter a valid email address.
</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
}
//This is where Im having problem. From this point the form doesn't go on.
$verify_result= $_POST['verify_result'];
$verify = $_POST["verify"];
if(trim($verify) == '') {
$error = '<div class="error_message">Attention! Please enter the verification number.</div>';
} else if(trim($verify) != $verify_result) {
$error = '<div class="error_message">Attention! The number you entered is incorrect.</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "info#myaddress.com";
$e_subject = 'You\'ve been contacted from an app web page ' . $name . '.';
$e_body = "You have been contacted using the app comments box on the above app web page, their additional message is as follows.\r\n\n";
$e_content = "\"$comments\"\r\n\n";
$e_reply = "$name $email";
$msg = $e_body . $e_content . $e_reply;
// mail($address, $e_subject, $msg, $app, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
// Email has sent successfully, echo a success page.
echo "<div id='success_page_apps'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you, your message has been submitted to us.</p>";
echo "</div>";
echo '<input type="button" value="Send Another" onClick="history.go(-1); return (true); ">';
}
}
if(!isset($_POST['contactus']) || $error != '') {
echo $error; ?>
<fieldset id="contact_apps">
<form method="post" action="#ContactForm">
<label for="email" accesskey="E"><span class="required"></span> Email</label>
<input name="email" type="text" id="email" size="33" value="<?php echo$email;?>"/>
<textarea name="comments" cols="50" rows="15" id="comments"><?php echo$comments;?></textarea>
//This is the 'Are you human?' message
<p><span class="required">*</span> Are you human?</p>
<label class="numbersq" for='verify' accesskey='V'><?php echo $num1; ?> + <?php echo $num2; ?> =</label>
<input class="numbersa" name="verify" type="text" id="verify" size="4" value=""/>
<input name="verify_result" type="hidden" size="4" value="<?php echo $num1+$num2; ?>" /><br />
<input name="contactus" type="submit" class="send" id="contactus" >
</form>
</fieldset>
<?PHP
}
?>
I've got a php / ajax form that works 100% ... but I need a few of the same form on the SAME page. Of course each of the forms will go to a different recipient.
I tried duplicating the form and it seems very complicated! I've tried submitting the duplicated form (with lots of edits to the duplicated form to try get it working) but no success
I don't know if what I am doing is right.
How the form goes is, I have a button when clicked, it toggleslides the div which contains the form... fill in the form, hit submit and an ajax success message pops up saying thank you
HTML FORM:
<body>
<div id="container">
<div id="accommodation_listing_options_box">
<ul id="accommodation_listing_options">
<li>Price Range: <a href="#" class="tooltip" style="cursor:help;" title="Mid-range
Accommodation"><img src="../mid-range-yellow.png" width="28" height="19"
align="absmiddle" style="padding-left:0px;" /></a></li>
<li><a href="#">View
Comments</a> <img src="../comments_bubble_small.png" width="18" height="16"
align="absmiddle" style="padding-left:5px;" /></li>
</ul>
</div>
<div id="quick_enquiry_box">Make Quick Enquiry</div>
<div style="clear:both; width:710px;"></div>
<div style="clear:both;"></div>
<div id="slide_panel">
<div id="contact">
<div id="message"></div>
<form method="post" action="contact.php" name="contactform"
id="contactform">
<div id="my_contact_left">
<label for="name" accesskey="U"><span class="required">*
</span>Name</label><br />
<input name="name" type="text" id="name" size="30" />
<br />
<label for="email" accesskey="E"><span class="required">*
</span>Email</label><br />
<input name="email" type="text" id="email" size="30" />
<br />
<label for="phone" accesskey="P"><span class="required">*
</span>Phone:</label><br />
<input name="phone" type="text" id="phone" size="30" />
<br />
<label for="dayin" accesskey="P">Day in:</label><br />
<input name="dayin" class="datepicker" type="text" id="dayin"
size="30" />
<br />
<label for="dayout" accesskey="P">Day out:</label><br />
<input name="dayout" class="datepicker2" type="text" id="dayout"
size="30" />
</div>
<div id="my_contact_right">
<label for="comments" accesskey="C"><span class="required">*
</span>Your Comments</label><br />
<textarea name="comments" cols="40" rows="3" id="comments"
style="width: 350px; height:100px;"></textarea>
<p><span class="required">*</span>Type the validation code in
below</p>
<div style="width:100px; height:40px; float:left;"><label
for="verify" accesskey="V"> <img src="image.php" alt="Image
verification" border="0"/></label></div>
<div style="width:310px; height:40px; float:right;"><input
name="verify" type="text" id="verify" size="6" value="" style="width: 50px;" />
<input type="submit" style="margin-left:112px;" class="submit"
id="submit" value="Send it!" /></div>
<div style="clear:both; width:410px;"></div>
</div>
<div style="clear:both; width:710px;"></div>
</form>
</div>
<div id="quick_form_wrapper_close"><a href="#"><img src="../close-panel-button.gif"
/></a></div>
</div>
</div>
</body>
If I make a duplicated form, what I need to change in the HTML code is the following:
action="contact.php" name="contactform"
id="contactform"
to:
action="contact2.php" name="contactform2"
id="contactform2"
Is this correct? Anything else I need to change in the HTML?
Moving onto the Javascript:
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$('#submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message").slideUp(750,function() {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
dayin: $('#dayin').val(),
dayout: $('#dayout').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message").show().delay(5000).fadeOut();
}
);
});
Do I need to make the field ID's different duplicating a form on the same page?
EG:
$.post(action, {
name2: $('#name2').val(),
email2: $('#email2').val(),
phone2: $('#phone2').val(),
dayin2: $('#dayin2').val(),
dayout2: $('#dayout2').val(),
comments2: $('#comments2').val(),
verify2: $('#verify2').val()
},
Do I need to do any changes to the PHP process form?
Here is the main part of the php process form:
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$dayin = $_POST['dayin'];
$dayout = $_POST['dayout'];
$comments = $_POST['comments'];
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits.</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.
</li>';
}
if($error != '') {
echo '<div class="error_message">Attention! Please correct the
errors below and try again.';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
// Advanced Configuration Option.
// i.e. The standard subject will appear as, "You've been contacted by
John Doe."
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Advanced Configuration Option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case
you must be sure to add them here.
$msg = "You have been contacted by $name with regards to Accommodation.
They passed verification and their message is as follows." . PHP_EOL . PHP_EOL;
$msg .= "$comments" . PHP_EOL . PHP_EOL;
$msg .= "You can contact $name via email, $email or via phone $phone." .
PHP_EOL . PHP_EOL;
$msg .= "We want to stay from the $dayin to the $dayout" . PHP_EOL .
PHP_EOL;
$msg .=
"---------------------------------------------------------------------------
-" . PHP_EOL;
if($twitter_active == 1) {
$twitter_msg = $name . " - " . $comments . ". You can contact " .
$name . " via email, " . $email ." or via phone " . $phone . ".";
twittermessage($twitter_user, $twitter_msg, $consumer_key,
$consumer_secret, $token, $secret);
}
$msg = wordwrap( $msg, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<strong>Email Sent Successfully.</strong>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!'; // Dont Edit.
}
}
Thanks in advance! Really appreciate your help because I have tried for hours and I haven't got it right yet!
EDIT:
MY CURRENT JAVASCRIPT CODING:
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$('.submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message").slideUp(750,function() {
$('#message').hide();
$.post(action, {
name: $('.name').val(),
email: $('.email').val(),
phone: $('.phone').val(),
dayin: $('.dayin').val(),
dayout: $('.dayout').val(),
comments: $('.comments').val(),
verify: $('.verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('.contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('.submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
jQuery(document).ready(function(){
$('.contactform2').submit(function(){
var action = $(this).attr('action');
$('.submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message2").slideUp(750,function() {
$('#message2').hide();
$.post(action, {
name: $('.name').val(),
email: $('.email').val(),
phone: $('.phone').val(),
dayin: $('.dayin').val(),
dayout: $('.dayout').val(),
comments: $('.comments').val(),
verify: $('.verify').val()
},
function(data){
document.getElementById('message2').innerHTML = data;
$('#message2').slideDown('slow');
$('.contactform2 img.loader').fadeOut('fast',function()
{$(this).remove()});
$('.submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message2").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
MY CURRENT JAVASCRIPT CODE:
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$(this).children('.submit').attr('disabled','disabled').after('<img
src="assets/ajax-loader.gif" class="loader" />');
$(this).children("#message").slideUp(750,function() {
$(this).children('#message').hide();
$.post(action, {
name: $(this).children('.name').val(),
email: $(this).children('.email').val(),
phone: $(this).children('.phone').val(),
dayin: $(this).children('.dayin').val(),
dayout: $(this).children('.dayout').val(),
comments: $(this).children('.comments').val(),
verify: $(this).children('.verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$(this).children('#message').slideDown('slow');
$(this).children('.contactform
img.loader').fadeOut('fast',function(){$(this).remove()});
$(this).children('.submit').removeAttr('disabled');
if(data.match('success') != null);
$(this).children("#message").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
Instead of using IDs for the jquery selectors, use classes. You can give all of the forms the same class name and the fields that are the same get the same classes as well.
Then, use those in your jquery:
$('.contactform').submit(function(){
$.post(action, {
name: $(this).children('.name').val(),
It should work for however many instances of the form you have because all of the input fields are referenced by $(this), which is the submitted form, regardless of id or name.
EDIT:
This should work for you. For any number of forms, this is all you would need.
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$('.submit', this).attr('disabled','disabled').after('<img src="assets/ajax-loader.gif" class="loader" />');
$('.message', this).slideUp(750,function() {
$('.message', this).hide();
$.post(action, {
name: $('.name', this).val(),
email: $('.email', this).val(),
phone: $('.phone', this).val(),
dayin: $('.dayin', this).val(),
dayout: $('.dayout', this).val(),
comments: $('.comments', this).val(),
verify: $('.verify', this).val()
},
function(data){
$('.message', this).html(data);
$('.message', this).slideDown('slow');
$('img.loader', this).fadeOut('fast',function() {
$(this).remove();
});
$('.submit', this).removeAttr('disabled');
if(data.match('success') != null);
$('.message', this).show().delay(5000).fadeOut();
});
});
return false;
});
});