在这种情况下,如何验证reCAPTCHA?

时间:2011-06-24 18:00:06

标签: php forms recaptcha

我知道isset($ a)不正确只是为了说明。如果我应用此代码,它没有任何东西(刷新页面)。那我该验证吗?

<?php
if (isset($a)) {

// entering data in database

if($result = mysql_query($sql ,$db)) {
// some code here

} else { 
echo "ERROR: ".mysql_error();
}
} else {
?>
<form method='post' action='' name='form' id='form' enctype='multipart/form-data'>
<?php
require_once('recaptchalib.php');
// Get a key from https://www.google.com/recaptcha/admin/create
$publickey = "mypublickey";
$privatekey = "myprivatekey";

# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;

# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);

 if ($resp->is_valid) {
$a = '';
         } else {
                # set the error code so that we can display it
                $error = $resp->error;
        }
}
echo recaptcha_get_html($publickey, $error);
?>
<input type="submit" id='button2' name="Submit" value="Submit it!" class="button2">

</form>
<?php
}
?>

1 个答案:

答案 0 :(得分:3)

首先:要检查表单是否已提交,您可以检查$_SERVER - 数组的REQUEST_METHOD键。根据PHP.net,这表明使用了哪种请求方法来访问页面;即'GET','HEAD','POST','PUT'。因此,以下行可以解决问题:if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

其次,reCAPTCHA Developer Guilde准确描述了如何显示验证码图像并检查验证码是否正确填写。我稍微修改了您的代码示例,因此您可以了解应该如何继续。没有经过严格考验!

<?php
/* Require the recaptcha library, file-globally */
require_once('recaptchalib.php');

/* Get a key from https://www.google.com/recaptcha/admin/create */
$publickey = "mypublickey";
$privatekey = "myprivatekey";

/* Check wether the form was submitted */
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

    /* Check wether the captcha was correct */
    $resp = recaptcha_check_answer( $privatekey, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field'] );

    /* Was it ? */
    if ( ! $resp->is_valid ) {

        /* What happens when the CAPTCHA was entered incorrectly */
        die( "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")" );

    } else {

        /* Entering data in database */
        if ( $result = mysql_query( $sql, $db ) ) {

            /* Some code here */

        } else {

            echo "ERROR: ".mysql_error( );

        }

    }

/* The form isn't posted yet, so we show the form */
} else {

    ?>

    <form method='post' action='' name='form' id='form' enctype='multipart/form-data'>
        <?php
        /* This is all we need to display the recaptcha */
        echo recaptcha_get_html($publickey);
        ?>
        <input type="submit" id='button2' name="Submit" value="Submit it!" class="button2">
    </form>

    <?php
}
?>