如何使用使用php_self操作的表单设置recaptcha

时间:2017-01-19 20:19:46

标签: php forms curl recaptcha

我的网站看起来像这样。

<?php
  include 'dbd.php';     //DB Login details
?>
<!DOCTYPE html> 
<html> 
<head>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head> 

<body>

<?php        
$showFormular = true;

if (isset($_POST['submit'])) {
    $error = false;

    if (!$error) {
      $statement = $pdo->prepare("INSERT INTO table (email, name) VALUES (:email, :name,)");
        $result    = $statement->execute(array(
            'email' => $email,
            'name' => $name
        ));

        if ($result) {
            echo "Your Registration was Successful";
            $showFormular = false;
        } else {
            echo 'Could not register your Account';
        }

    }
}

if ($showFormular) {
?>

<form action="<?php echo ($_SERVER['PHP_SELF']); ?>" method="post">

    <input placeholder="Your Forum Name Here" name="name" required>
    <input placeholder="Your Forum Email Here" name="email" required>
    <div class="g-recaptcha" data-sitekey="public key"></div>

    <input name="submit" type="submit">
</form>

<?php
}
?>

</body>
</html>

我遇到的问题是我不知道如何实施Serverside ReCaptcha Check。我尝试使用以下方法,但是我明显得到了函数为空的错误,因为它直接执行了。

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
    CURLOPT_POST =>1,
    CURLOPT_POSTFIELDS => [
        'secret' => 'privat key',
        'response' => $_POST['g-recaptcha-response'],
        ],
]);

我希望我解释得足够好,有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

为什么要尝试使用curl命令?您可以直接使用php代码执行此操作。

首先下载这个php reCaptcha库并导入你的项目:reCaptcha gitHub

其次,在你动作之后调用你的php并在你的php代码上实现它。

require_once('your-imported-autoload.php-path'); ex:Assets/reCaptcha/autoload.php

  $privatekey = "-your private key-";

  $recaptcha = new \ReCaptcha\ReCaptcha($privatekey);

  $resp = $recaptcha->verify($_POST['g-recaptcha-response'],  

  $_SERVER['REMOTE_ADDR']);

  if (!$resp->isSuccess()) {

    // 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 {
    // Your code here to handle a successful verification

  }

最后,对于cURL,您尝试通过SSL连接并且必须处理它

curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);