PHP форма и Invisible reCAPTCHA

Решение, как подключить невидимую капчу от Google reCAPTCHA Invisible к PHP форме

PHP форма и Invisible reCAPTCHA

Решение:
  1. Получить API ключи по ссылке
  2. В подвал код:
    <script src='https://www.google.com/recaptcha/api.js?hl=ru'></script>
    <script>
        function onSubmit(token) {
            document.getElementById("i-recaptcha").submit();
        }
    </script>
    
  3. Форма:
    <form action="handle.php" method="POST" id="i-recaptcha">
        <input type="text" name="text" value="Тест">
        <button class="g-recaptcha" data-sitekey="_____КЛЮЧ_____" data-callback="onSubmit">Отправить</button>
    </form>
  4. Файл handle.php
    <?php
        function post_captcha($user_response) {
            $fields_string = '';
            $fields = array(
                'secret' => '_____СЕКРЕТНЫЙ_КЛЮЧ_____',
                'response' => $user_response
            );
            foreach($fields as $key=>$value)
            $fields_string .= $key . '=' . $value . '&';
            $fields_string = rtrim($fields_string, '&');
    
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
            curl_setopt($ch, CURLOPT_POST, count($fields));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
    
            $result = curl_exec($ch);
            curl_close($ch);
    
            return json_decode($result, true);
        }
    
        // Call the function post_captcha
        $res = post_captcha($_POST['g-recaptcha-response']);
    
        if (!$res['success']) {
            // Если капча не правильная
            echo 'reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.';
        } else {
            // Если капча правильная
            echo $_POST['text'];
            echo '<br><p>CAPTCHA was completed successfully!</p><br>';
        }
    ?>

Комментарии (0)

Похожие решения:
Изменено: 18 01 2021
Просмотров: 2498