Google reCAPTCHA server端PHP的寫法(v2、v3)

v3版本


$msg = array();

$secret = 'your_secret_key';
$gRecaptchaResponse = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : null;
$ip = $_SERVER['REMOTE_ADDR'];
$domainName = $_SERVER['HTTP_HOST'];

include_once ("recaptcha/src/autoload.php");
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
  $resp = $recaptcha->setExpectedHostname($domainName)
                  ->setExpectedAction('homepage')
                  ->setScoreThreshold(0.5)
                  ->verify($gRecaptchaResponse, $ip);
  if ($resp->isSuccess()) {
    // $msg['ending']=$resp->toArray();
  } else {
    $errors = $resp->getErrorCodes();
    $msg['ending']='recaptchaFail';
    $msg['recaptcha']=$errors;
    echo json_encode($msg);
    exit();
  }
其中,autoload.php是官方在github給的檔案:

/* An autoloader for ReCaptcha\Foo classes. This should be required()
 * by the user before attempting to instantiate any of the ReCaptcha
 * classes.
 */

spl_autoload_register(function ($class) {
    if (substr($class, 0, 10) !== 'ReCaptcha\\') {
        /* If the class does not lie under the "ReCaptcha" namespace,
         * then we can exit immediately.
         */
        return;
    }

    /* All of the classes have names like "ReCaptcha\Foo", so we need
     * to replace the backslashes with frontslashes if we want the
     * name to map directly to a location in the filesystem.
     */
    $class = str_replace('\\', '/', $class);

    /* First, check under the current directory. It is important that
     * we look here first, so that we don't waste time searching for
     * test classes in the common case.
     */
    $path = dirname(__FILE__).'/'.$class.'.php';
    if (is_readable($path)) {
        require_once $path;

        return;
    }

    /* If we didn't find what we're looking for already, maybe it's
     * a test class?
     */
    $path = dirname(__FILE__).'/../tests/'.$class.'.php';
    if (is_readable($path)) {
        require_once $path;
    }
});

v2版本


$msg = array();

$response = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : null;
$privatekey = 'your_secret_key';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$privatekey.'&response='.$response);
$responseData = json_decode($verifyResponse);
if($responseData->success){
  // $msg['captcha'] = 'success';
}else{
  $msg['captcha'] = $responseData;
  echo json_encode($msg);
}

留言

這個網誌中的熱門文章

用CSS的 min() max() 與vw,設計有極限值的RWD響應式文字

10 steps、「ライブ会場を沸らせる、フロアを沸かす」ミーム動画の作り方 (Viggle AI)

運用資料層 dataLayer.push 建立 GTM 自訂事件