Jump to content

Validating Recaptcha on same page with pre-existing form


mkultron

Recommended Posts

Hi guys, I'm having problems integrating Recaptcha into an existing form. I want it all to process on the same page. I took a look on Google and found a pre-existing script which does what I want but I'm still having trouble integrating it with what I already have, form fields and the recaptcha validate seperately. Here's my script so far:

 

before the <html> tag:

 

<?php session_start(); ?>

<?php
// DEMO to use reCAPTCHA library on a form
//
//	courtesy Spectrum Nashville
//	http://www.spectrum-nashville.com
//	
//  provide the Public Key and Private Key for your account here:

define( API_PUBLIC_KEY, '6LeNt84SAAAAAAH0Et-eJpNeuYO-kRXgrpcXML36' );
define( API_PRIVATE_KEY, '6LeNt84SAAAAAMlGWZUEHqFHncRyvaYbI5YdE8BY'  );

//
//	once the keys have been provided above, this demo should work without any further changes to the code below
//
//	include the recaptcha library file here
//
require_once('recaptchalib.php');
//
//	the $validated variable will switch to true in the code below if a valid CAPTCHA is submitted (see code below).
//	do not change this.
//
$validated = false;
?>

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
	$hasError = true;
} else {
	$name = trim($_POST['name']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '')  {
	$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
	$hasError = true;
} else {
	$email = trim($_POST['email']);
}

//Check to make sure comments were entered
if(trim($_POST['comment']) == '') {
	$hasError = true;
} else {
	if(function_exists('stripslashes')) {
		$comment = stripslashes(trim($_POST['comment']));
	} else {
		$comment = trim($_POST['comment']);
	}
}

//If there is no error, send the email
if(!isset($hasError)) {
	$emailTo = 'eevansrange@gmail.com'; //Put your own email address here
	$subject = "Feedback from TEST FORM";
	$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comment";
	// $body = "Enquiry type: $enquiry \n\nName: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
	$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

	mail($emailTo, $subject, $body, $headers);
	$emailSent = true;
}
}
?>

 

 

Within body tag:

 

<!-- RECAPTCHA START -->
<script>
// example of using JavaScript variable to provide "theme" control
// of the reCAPTCHA element. This entire <script> block is optional.
    var RecaptchaOptions = {
       theme : 'blackglass',
       tabindex : 2
    };
    </script>
<!-- RECAPTCHA END -->




	<section id="form">

		<h2 class="blue">CONTACT ME</h2>

		<div id="form-holder">

			<p class="form-instructions">Need some work doing? Have a comment? Post them below and I'll get back to you asap!</p>

			<?php if(isset($hasError)) { //If errors are found ?>
			<p class="errors">Please check you've filled out the fields correctly.</p>
			<?php } ?>

			<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
			<p class="success">Thank you <strong><?php echo $name;?></strong>, your email has been sent.</p>
			<?php } ?>

<?php 
//	see the form below and look for the hidden input named 'validate' to see how this works. This is a nice flag to
//	indicate to us that the validation should be attempted. The first time a user browses to this page, there will be
//	no 'validate' variable in the $_POST[] array, so no validation is attempted and no error message will be generated.
//
//	do not change any of this code.
//
if( $_POST['validate'] === 'yes' ) { 
	$response = recaptcha_check_answer( API_PRIVATE_KEY,
									   	$_SERVER['REMOTE_ADDR'],
										$_POST['recaptcha_challenge_field'],
										$_POST['recaptcha_response_field']
										);

	if( ! $response->is_valid ) {		
		//
		// captcha failed -- display the error message
		//
		//	change this to whatever message you want to display. you could even perform other form validations
		//	and display messages about other required fields, etc., here if you want.
		//	use the CSS in the <head> section above to determine how your error message "box" will appear.
		//
		echo '<div id="recaptcha_error_box">The reCAPTCHA failed with this message: '.$response->error.'<br />Please try again.</div>';
		// by default now, let the flow-of-control fall back into the <form> below so the user can try again
	}
	else {
		//	set $validated to true so we know later in our document not to show the form again
		//	don't change this.
		$validated = true;
		//
		//	YOUR CODE HERE....
		//
		// at this point, th form was submitted with valid reCAPTCHA, so go do whatever you wanted to do.
		// for the demo, we'll just echo back the values from the form.
		//
		//	you could also send an email message, add or update database records, etc.
		//
		?>
            <?php
	}	/* end if( ! is_valid ) */

 } /* end if($_POST['validate']==='yes') */ 
?>	 
<?php if( ! $validated ) { ?>
  
  
  
  

  
  

			<form class="cmxform" id="commentForm" method="post" border="0" action="<?php echo $_SERVER['PHP_SELF']; ?>#form"><!-- added #form so on submit the page anchors to the form div rather than taking you back to the top of the page -->
				<?php
				  require_once('recaptchalib.php');
				  $publickey = "6LeNt84SAAAAAAH0Et-eJpNeuYO-kRXgrpcXML36"; // you got this from the signup page
				  echo recaptcha_get_html($publickey);
				?>
				<!--<input type="submit" />-->
				<br />

				<label class="required" for="name" title="Enter your name"><span>Name</span><input type="text" id="name" name="name" size="50" class="required" value="<?php echo stripslashes(htmlentities($_POST['your_name'])); ?>" /></label>
				<label class="required" for="email" title="Enter your email"><span>Email</span><input type="text" id="email" name="email" size="50" class="required" value="<?php echo stripslashes(htmlentities($_POST['your_email'])); ?>" /></label>
				<label class="required" for="comment" title="Enter your comments" size="50" value="<?php echo stripslashes(htmlentities($_POST['comment'])); ?>">
				<span>Comments</span><textarea name="comment" rows="5" cols="50" class="required"></textarea>
				</label>

<!-- CAPTCHA START -->			

<?php echo recaptcha_get_html(API_PUBLIC_KEY); ?>

<!-- CAPTCHA END -->

				<input type="hidden" name="validate" value="yes" />
				<!--<input type="submit" value="Try It" />-->
				<label for="submit" class="nocontent"><input class="submit" type="submit" name="submit" value="Try It" title="Send form" />Items marked <img src="images/required-2.png" width="12" height="12" alt="required field" /> are required fields</label>
				<!-- need to include the name tag =submit above for the form to process and send the email -->
				<!-- class="nocontent" - commmented out of above label -->					
			</form>
<?php } /* end if( ! $validated ) */ ?>

		</div>

	</section>












<!-- client-side validation -->
<script type="text/javascript">
	jQuery(function(){
		// Grab each form element
		jQuery("label[title]").each(function(){
			jQuery(this).append("<div class=\"infopop\">");	
			titletext = jQuery(this).attr("title");
			jQuery(this).removeAttr("title");
			jQuery(".infopop",this).css({opacity:0}).html(titletext);

			jQuery("input",this).focus(function(){
				// Mouseover
				doFocus(this);
			}).blur(function(){
				// MouseOut
				doBlur(this);
			});

			/* ADDED TO show errors for textarea */
			jQuery("textarea",this).focus(function(){
				// Mouseover
				doFocus(this);
			}).blur(function(){
				// MouseOut
				doBlur(this);
			});

		});
	});

	function doFocus(obj) {
		jQuery(obj).addClass("active").parents("label").addClass("active").find(".infopop").animate({opacity:1,left:492},500);
	}

	function doBlur(obj) {
		if (validate(obj)) { 
			isGood(obj);
		}
	}

	function reportErr(obj, message) {
		jQuery(obj).addClass("error").parents("label").removeClass("isgood").addClass("required").addClass("error").find(".infopop").html(message).addClass("errorpop").animate({opacity:1,left:492},500);
	}

	function isGood(obj) {
		jQuery(obj).removeClass("error").removeClass("active").parents("label").addClass("isgood").removeClass("error").removeClass("active").find(".infopop").removeClass("errorpop").animate({opacity:0,left:513},500);
	} 			

	function validate(obj) {
		mask = jQuery.extend({textfieldmask: /^[a-z\.\s-]{5,}$/i,emailmask: /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i,commentsboxmask: /^[a-z\.\s-]{5,}$/i});
		errmsg = jQuery.extend({textfielderr:"5 or more letters",emailerr:"Invalid address",matcherr: "Must match",commenterr: "5 or more letters"});
		var masktouse = null;
		var mustmatch = null;

		switch(obj.name) {
			case "name": 		masktouse="textfieldmask"; 		errtouse="textfielderr"; 	break;
			case "email": 		masktouse="emailmask"; 			errtouse="emailerr"; 		break;
			case "comment": 	masktouse="commentsboxmask"; 	errtouse="commenterr"; 		break;
		}

		// Check that the element is a required field before validating against it.
		if(jQuery(obj).parents("label").hasClass("required") && masktouse) {
			// Set up a quick way of accessing the object we're validating
			pointer = jQuery(obj);
			// Test the value of the field against the Regular Expression
			if (mask[masktouse].test(pointer.val())) {
				// The field validated successfully!

				// Check to see if the field needs to match another field in the form
				if (mustmatch) {
					// It does need to match, so grab the object it needs to match
					matchobj = jQuery("#"+mustmatch);
					if (matchobj.val()!='' && matchobj.val()!=pointer.val()) {
						// The fields don't match, so report an error on both of them
						reportErr(obj,errmsg["matcherr"]);	
						reportErr(matchobj,errmsg["matcherr"]);
					}
					else {
						// Either the fields match, or the other field hasn't been completed yet
						// If the other field has been completed, call the isGood function to clear any error message showing
						if (matchobj.val()!='') { isGood(matchobj);}
						return true;
					}
				}
				else {
					// No match is required, so return true - validation passed!
					return true;
				} 
			}
			else { 
				// The field failed to validate against the Regular Expression
				reportErr(obj,errmsg[errtouse]);
				return false; 
			}
		} 
		else {	
			// This isn't a required field, so we won't validate it against anything			
			return true;
		}
	}
</script>

 

 

Any help would be much appreciated

 

MK

 

Link to comment
Share on other sites

extract the essence of what you want to do into a small example program and get that working, then insert that into your own.

 

for example just validate the catcha and find out what you have to do to get it working on its own or make one field in a form.

start with small mickey-mouse php programs then when you understand how to do whatever it is you need to do... then stick it into your program.

Thats what I do. Keep things very simple. :-)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.