fail response without reloading form

69 views
Skip to first unread message

Bonny

unread,
Jul 10, 2007, 5:10:02 PM7/10/07
to reCAPTCHA
Hello there,

I put reCAPTCHA at the end of my form. When the answer is not correct
the page reloads again with fields reset. Does any one know how to
keep the fields still filled, and display a message saying something
like " Please reEnter your answer..." or something like that when
there's a failed answer? Below is my code and thanks a million !!

-----code-------

<?php
require_once('recaptchalib.php');

define('PUBLIC_KEY', 'my public key');
define('PRIVATE_KEY', 'my private key');

$error = null;

if ($_POST["recaptcha_response_field"]) {
$response = recaptcha_check_answer(
PRIVATE_KEY, $_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);

if ( $response->is_valid ) {

//this is my mailer function//

$to = "bla...@gmail.com";
$subject = "Hinc Showroom Website Feedback";
$first_name_field = $_POST['first_name'];
$last_name_field = $_POST['last_name'];
$dropdown= $_POST['drop_down'];
$email_field = $_POST['email'];
$phone = $_POST['phone'];
$adress = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$message = $_POST['message'];
$signup = $_POST['signup'];


$body = "From: $first_name_field $last_name_field
\n Status:$dropdown\n Email:$email_field\n Phone: $phone\n Address:
$adress\n City:$city\n State: $state\n Zipcode: $zipcode\n Message:
$message\n Sign up for newsletter:$signup\n";

header('Location: home.php');

mail($to, $subject, $body);
//end of my mailer function//

}
else {
$error = $response->error;
}
}

echo recaptcha_get_html( PUBLIC_KEY, $error );
?>


-----code end here------

Thank you again!

reCAPTCHA Support

unread,
Jul 10, 2007, 5:57:03 PM7/10/07
to reca...@googlegroups.com
You should handle a reCAPTCHA failure just as you do any other type of failure (eg, if a person forgets to fill out a field). You can do this by echoing back the values of the fields in the HTML you generate.
--
reCAPTCHA: stop spam, read books
http://recaptcha.net

jeremyers1

unread,
Sep 4, 2007, 1:29:38 PM9/4/07
to reCAPTCHA
Let me begin by stating I am a complete coding moron and so need baby
steps here.

Having said that, I have the same problem as the original poster with
my Wordpress blog, but the answer doesn't make any sense to me. I
don't know how to echo back the values of the fields in the HTML I
generate. I checked the documentation, but couldn't understand that
either. As I said, I think I'm a coding moron.

On a related note, I am not getting an error message generated
either.

So, can you please tell me exactly what to put in the code below, and
exactly where it should go so that I get (1) an error message telling
people to try again, and (2) their comment reappearing in the comment
box so they don't have to retype it? Thanks.

Ideally, just paste the correct code sections as a reply.


Here is my recaptcha code (with the keys removed):


<?php
/*
Plugin Name: reCAPTCHA
Plugin URI: http://recaptcha.net/plugins/wordpress
Description: Integrates a reCAPTCHA with wordpress
Version: 2.5
Author: Ben Maurer & Mike Crawford
Email: sup...@recaptcha.net
Author URI: http://bmaurer.blogspot.com
*/

require_once (dirname(__FILE__) . '/recaptchalib.php');
$recaptcha_opt = get_option('plugin_recaptcha');

#doesn't need to be secret, just shouldn't be used by any other code.
define ("RECAPTCHA_WP_HASH_SALT", "PUBLIC KEY WAS HERE");

function recaptcha_wp_hash_comment ($id)
{
global $recaptcha_opt;
if (function_exists('wp_hash') ) {
return wp_hash (RECAPTCHA_WP_HASH_COMMENT . $id);
} else {
return md5 (RECAPTCHA_WP_HASH_COMMENT . $recaptcha_opt['privkey'] .
$id);
}
}

function recaptcha_wp_get_html ($recaptcha_error)
{
global $recaptcha_opt;
return recaptcha_get_html($recaptcha_opt['pubkey'],
$recaptcha_error);
}

/**
* Embeds the reCAPTCHA widget into the comment form.
*
*/
function recaptcha_comment_form() {
//modify the comment form for the reCAPTCHA widget
$recaptcha_js_opts = <<<OPTS
<script type='text/javascript'>
var RecaptchaOptions = { theme : 'red', tabindex : 5 };
</script>
OPTS;
$comment_string = <<<COMMENT_FORM
<div id="recaptcha-submit-btn-area"></div>
<script type='text/javascript'>
var sub = document.getElementById('submit');
sub.parentNode.removeChild(sub);
document.getElementById('recaptcha-submit-btn-area').appendChild
(sub);
document.getElementById('submit').tabIndex = 6;
if ( typeof _recaptcha_wordpress_savedcomment != 'undefined') {
document.getElementById('comment').value =
_recaptcha_wordpress_savedcomment;
}
</script>
<noscript>
<style type='text/css'>#submit {display:none;}</style>
<input name="submit" type="submit" id="submit-alt" tabindex="6"
value="Submit Comment"/>
</noscript>
COMMENT_FORM;
echo $recaptcha_js_opts . recaptcha_wp_get_html($_GET['rerror']) .
$comment_string;
}


add_action( 'comment_form', 'recaptcha_comment_form' );


function recaptcha_wp_show_captcha_for_comment () {
global $user_ID;
return true;
}


$recaptcha_saved_error = '';

/**
* Checks if the reCAPTCHA guess was correct and sets an error session
variable if not
* @param array $comment_data
* @return array $comment_data
*/
function recaptcha_wp_check_comment($comment_data) {

global $user_ID, $recaptcha_opt;
global $recaptcha_saved_error;

if (recaptcha_wp_show_captcha_for_comment ()) {
if ( $comment_data['comment_type'] == '' ) { // Do not check
trackbacks/pingbacks

$challenge = $_POST['recaptcha_challenge_field'];
$response = $_POST['recaptcha_response_field'];

$recaptcha_response = recaptcha_check_answer ($recaptcha_opt
['privkey'], $_SERVER['REMOTE_ADDR'], $challenge, $response);
if ($recaptcha_response->is_valid) {
return $comment_data;
}
else {
$recaptcha_saved_error = $recaptcha_response->error;

add_filter('pre_comment_approved', create_function('$a', 'return
\'spam\';'));
return $comment_data;
}
}
}
return $comment_data;
}


/*
* If the reCAPTCHA guess was incorrect from
recaptcha_wp_check_comment, then redirect back to the comment form
* @param string $location
* @param OBJECT $comment
* @return string $location
*/
function recaptcha_wp_relative_redirect($location, $comment) {
global $recaptcha_saved_error;
if($recaptcha_saved_error != '') {
//replace the '#comment-' chars on the end of $location with
'#commentform'.

$location = substr($location, 0,strrpos($location, '#')) .
((strrpos($location, "?") === false) ? "?" : "&") .
'rcommentid=' . $comment->comment_ID .
'&rerror=' . $recaptcha_saved_error .
'&rchash=' . recaptcha_wp_hash_comment ($comment->comment_ID) .
'#commentform';

}
return $location;
}


/*
* If the reCAPTCHA guess was incorrect from
recaptcha_wp_check_comment, then insert their saved comment text
* back in the comment form.
* @param boolean $approved
* @return boolean $approved
*/
function recaptcha_wp_saved_comment() {
if ( !is_single() && !is_page() )
return;

if ($_GET['rcommentid'] && $_GET['rchash'] ==
recaptcha_wp_hash_comment ($_GET['rcommentid'])) {
$comment = get_comment($_GET['rcommentid']);
echo "<script type='text/javascript'>
var _recaptcha_wordpress_savedcomment = '" . rawurlencode($comment-
>comment_content) ."';
_recaptcha_wordpress_savedcomment =
unescape(_recaptcha_wordpress_savedcomment);
</script>";
wp_delete_comment($comment->comment_ID);
}

}

function recaptcha_wp_blog_domain ()
{
$uri = parse_url(get_settings('siteurl'));
return $uri['host'];
}

add_filter('wp_head', 'recaptcha_wp_saved_comment',0);
add_filter('preprocess_comment', 'recaptcha_wp_check_comment',0);
add_filter('comment_post_redirect', 'recaptcha_wp_relative_redirect',
0,2);

function recaptcha_wp_add_options_to_admin() {
if (function_exists('add_options_page')) {
add_options_page('reCAPTCHA', 'reCAPTCHA', 8,
plugin_basename(__FILE__), 'recaptcha_wp_options_subpanel');
}
}

function recaptcha_wp_options_subpanel() {

$optionarray_def = array(
'pubkey' => '',
'privkey' => '',
);

add_option('plugin_recaptcha', $optionarray_def, 'reCAPTCHA
Options');

/* Check form submission and update options if no error occurred */
if (isset($_POST['submit']) ) {
$optionarray_update = array (
'pubkey' => $_POST['recaptcha_opt_pubkey'],
'privkey' => $_POST['recaptcha_opt_privkey'],
);
update_option('plugin_recaptcha', $optionarray_update);
}

/* Get options */
$optionarray_def = get_option('plugin_recaptcha');


?>

<!-- ############################## BEGIN: ADMIN OPTIONS
################### -->
<div class="wrap">


<h2>reCAPTCHA Options</h2>
<p>reCAPTCHA asks commenters to read two words from a book. One of
these words proves
that they are a human, not a computer. The other word is a word
that a computer couldn't read.
Because the user is known to be a human, the reading of that word
is probably correct. So you don't
get comment spam, and the world gets books digitized. Everybody
wins! For details, visit
the <a href="http://recaptcha.net/">reCAPTCHA website</a>.</p>

<form name="form1" method="post" style="margin: auto; width: 25em;"
action="<?php echo $_SERVER['PHP_SELF'] . '?page=' .
plugin_basename(__FILE__); ?>&updated=true">


<!-- ****************** Operands ****************** -->
<fieldset class="options">
<legend>reCAPTCHA Key</legend>
<p>
reCAPTCHA requires an API key, consisting of a "public" and a
"private" key. You can sign up for a

<a href="<?php echo recaptcha_get_signup_url
(recaptcha_wp_blog_domain (), 'wordpress');?>" target="0">free
reCAPTCHA key</a>.
</p>
<label style="font-weight:bold" for="recaptcha_opt_pubkey">Public
Key:</label>
<br />
<input name="recaptcha_opt_pubkey" id="recaptcha_opt_pubkey"
size="40" value="<?php echo $optionarray_def['pubkey']; ?>" />
<label style="font-weight:bold" for="recaptcha_opt_privkey">Private
Key:</label>
<br />
<input name="recaptcha_opt_privkey" id="recaptcha_opt_privkey"
size="40" value="<?php echo $optionarray_def['privkey']; ?>" />

</fieldset>


<div class="submit">
<input type="submit" name="submit" value="<?php _e('Update
Options') ?> &raquo;" />
</div>

</form>

<p style="text-align: center; font-size: .85em;">&copy; Copyright
2007&nbsp;&nbsp;<a href="http://recaptcha.net">reCAPTCHA</a></p>

</div> <!-- [wrap] -->
<!-- ############################## END: ADMIN OPTIONS
##################### -->


<?php


}


/*
=============================================================================
Apply the admin menu
=============================================================================
*/

add_action('admin_menu', 'recaptcha_wp_add_options_to_admin');


if ( !($recaptcha_opt ['pubkey'] && $recaptcha_opt['privkey'] ) && !
isset($_POST['submit']) ) {
function recaptcha_warning() {
$path = plugin_basename(__FILE__);
echo "
<div id='recaptcha-warning' class='updated fade-
ff0000'><p><strong>reCAPTCHA is not active</strong> You must <a
href='options-general.php?page=" . $path . "'>enter your reCAPTCHA API
key</a> for it to work</p></div>
<style type='text/css'>
#adminmenu { margin-bottom: 5em; }
#recaptcha-warning { position: absolute; top: 7em; }
</style>
";
}
add_action('admin_footer', 'recaptcha_warning');
return;
}

?>


jeremyers1

unread,
Sep 4, 2007, 9:28:00 PM9/4/07
to reCAPTCHA
I found another Wordpress blog today that uses the reCaptcha:
http://www.davidmattison.ca/wordpress/?p=2114#comment-243333

I tried to enter a false comment, and it worked properly, both saving
my comment and telling me I had entered the words incorrectly.

So I posted a comment asking the owner of the blog to send me his
recaptcha code, which he gladly did. I then compared his code with my
code line by line. Aside from the public keys, there was not a single
difference between the two. My code exactly resembles his letter for
letter.

So, the problem must be with my WordPress theme/template? I really
like my template, and so don't just want to switch. Is there some
change I can make to the template somewhere? Maybe this is a question
I should be asking WordPress?

Any help you can offer is appreciated...

reCAPTCHA Support

unread,
Sep 4, 2007, 9:53:06 PM9/4/07
to reca...@googlegroups.com
Hi,

You might try using the default theme. We have seen themes causing issues before.

jeremyclarke

unread,
Apr 29, 2008, 3:05:20 PM4/29/08
to reca...@googlegroups.com
Not sure why I can't reply to this old thread but wanted to post the
solution I found.

Problem was: in Wordpress plugin, a failed captcha reloaded the page
but didn't replace the comment text in the comment form, forcing the
person to rewrite it (and maybe making them think it was actually
posted).

My solution: Check for the presence and location of the comment form
API hook (which recaptcha uses to load the javascript holding the
deleted comment text). It looks like this:

<?php do_action('comment_form', $post->ID); ?>

In my case it actually WAS in the comment form, but in a slightly
different location from where it is in the default wordpress theme.
Putting it at the end of the form immediately before the </form> made
the comment form load the text as expected.

<p id="submit">
<input name="submit" type="submit" tabindex="5" value="Post
Comment" />
</p>
<?php do_action('comment_form', $post->ID); ?>
</form>

Not sure if that constitutes a bug or not (the js involved seems
simple enough and I can't see why moving the hood down a few lines
would fix it but I'm not a js programmer so there you go). Having it
work so long as the hook is called somewhere in the comments template
would definitely be preferrable as many people probably experience
this bug without noticing it (i run a site with a very international
audience, who I think probably fail the captchas more than average,
and they've been complaining about censorship lately ;)

Jeremy Clarke | http://simianuprising.com
Code and Design | http://globalvoicesonline.org

---------- Forwarded message ----------
From: "reCAPTCHA Support" <supp...@recaptcha.net>
Date: Sep 4 2007, 9:53 pm
Subject: fail response without reloading form
To: reCAPTCHA


Hi,

You might try using the default theme. We have seen themes causing
issues
before.

On 9/4/07, jeremyers1 <jeremye...@gmail.com> wrote:





> I found another Wordpress blog today that uses the reCaptcha:
>http://www.davidmattison.ca/wordpress/?p=2114#comment-243333

> I tried to enter a false comment, and it worked properly, both saving
> my comment and telling me I had entered the words incorrectly.

> So I posted a comment asking the owner of the blog to send me his
> recaptcha code, which he gladly did. I then compared his code with my
> code line by line. Aside from the public keys, there was not a single
> difference between the two. My code exactly resembles his letter for
> letter.

> So, the problem must be with my WordPress theme/template? I really
> like my template, and so don't just want to switch. Is there some
> change I can make to the template somewhere? Maybe this is a question
> I should be asking WordPress?

> Any help you can offer is appreciated...

Reply all
Reply to author
Forward
0 new messages