Home  >  Q&A  >  body text

How to verify Google reCAPTCHA v3 on the server side?

<p>I just set up the new Google Captcha with checkboxes and it works fine on the front end, but I don't know how to handle it on the server side using PHP. I tried using the old code below but the form is sent even though the verification code is invalid. </p> <pre class="brush:php;toolbar:false;">require_once('recaptchalib.php'); $privatekey = "my key"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { $errCapt='<p style="color:#D6012C ">The CAPTCHA Code was not entered correctly.</p>';}</pre> <p><br /></p>
P粉904191507P粉904191507442 days ago639

reply all(2)I'll reply

  • P粉297434909

    P粉2974349092023-08-28 12:23:43

    Private Key Security

    While the answers here certainly work, they use GET requests, which exposes your private key (even with https ). On Google Developers, the specified method is POST< /代码>.

    For more details: https://stackoverflow.com/a/323286/1680919

    Verify via POST

    function isValid() 
    {
        try {
    
            $url = 'https://www.google.com/recaptcha/api/siteverify';
            $data = ['secret'   => '[YOUR SECRET KEY]',
                     'response' => $_POST['g-recaptcha-response'],
                     'remoteip' => $_SERVER['REMOTE_ADDR']];
                     
            $options = [
                'http' => [
                    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method'  => 'POST',
                    'content' => http_build_query($data) 
                ]
            ];
        
            $context  = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            return json_decode($result)->success;
        }
        catch (Exception $e) {
            return null;
        }
    }

    Array syntax: I use the "new" array syntax ([ and ] instead of array(..)< /代码>). If your version of php doesn't support this yet, you will have to edit these 3 array definitions accordingly (see comments).

    Return value: If the user is valid, this function returns true; if it is invalid, it returns false; if the user is valid, it returns nullIf an error occurs. For example, you can use it simply by writing if (isValid()) { ... }

    reply
    0
  • P粉262113569

    P粉2621135692023-08-28 10:59:16

    This is the solution

    index.html

    <html>
      <head>
        <title>Google recapcha demo - Codeforgeek</title>
        <script src='https://www.google.com/recaptcha/api.js'></script>
      </head>
      <body>
        <h1>Google reCAPTHA Demo</h1>
        <form id="comment_form" action="form.php" method="post">
          <input type="email" placeholder="Type your email" size="40"><br><br>
          <textarea name="comment" rows="8" cols="39"></textarea><br><br>
          <input type="submit" name="submit" value="Post comment"><br><br>
          <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
        </form>
      </body>
    </html>

    verification.php

    <?php
        $email; $comment; $captcha;
    
        if(isset($_POST['email']))
            $email=$_POST['email'];
        if(isset($_POST['comment']))
            $comment=$_POST['comment'];
        if(isset($_POST['g-recaptcha-response']))
            $captcha=$_POST['g-recaptcha-response'];
    
        if(!$captcha){
            echo '<h2>Please check the the captcha form.</h2>';
            exit;
        }
    
        $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
        if($response['success'] == false)
        {
            echo '<h2>You are spammer ! Get the @$%K out</h2>';
        }
        else
        {
            echo '<h2>Thanks for posting comment.</h2>';
        }
    ?>

    http://codeforgeek.com/2014/12/google-recaptcha-tutorial /

    reply
    0
  • Cancelreply