简体   繁体   中英

Google ReCaptcha V2 not working with old PHP Code

I have a small website that I use for an organisation and recently we have been flooded with spam email from our contact page. I wish to add Googl ReCapture and I am having some issues with verifying and it submiting the form.

So the website would check the fields are not empty and then allow the user to send a message. But now it won't error check the fields and won't submit or send the email. Also when you visit the contact us page it displays the message "Thank you for contacting... UK, we will get back to you shortly." before even entering or clicking submit.

<?php
include ('includes/config.php');
$error = array();
$name = '';
$email = '';
$telephone = '';
$message = '';

//I have blanked my sitekey and secret key out
$siteKey = 'MY_SITE_KEY';
$secretKey = 'MY_SECRET_KEY';

if (isset($_POST['Send']))
{
    // Assign form data
    $name = $_POST['Name'];
    $email = $_POST['Email'];
    $telephone = $_POST['Telephone'];
    $message = $_POST['Message'];

    // Validate reCAPTCHA box 
        if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ 
            // Google reCAPTCHA API secret key 
            $secretKey = 'Your_reCAPTCHA_Secret_Key'; 

            // Verify the reCAPTCHA response 
            $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);  
            // Decode json data 
            $responseData = json_decode($verifyResponse); 

            // If reCAPTCHA response is valid 
            if($responseData->success){ 

    // Check for errors
    if (empty($name)) { $error[] = 'Name'; }
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { $error[] = 'Email'; }
    if (empty($telephone)) { $error[] = 'Telephone'; }
    if (empty($message)) { $error[] = 'Message'; }

    // If no errors
    if (sizeof($error) < 1) {
        // Build message
        $message = "Name: $name \n Email: $email \n Telephone: $telephone \n" . $message;

        // Send email
        mail('info@MYEMAIL.co.uk', "Message From $name", $message);

        // Reset form
        $name = '';
        $email = '';
        $telephone = '';
        $message = '';
    }
}}}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

</head>
<body>
<?php include ('includes/header.php'); ?>
<div id="wrapper">
    <div id="main">
        <h1>Contact Us</h1>
        <?php
        if (sizeof($error) > 0)
        {
            echo '<p>There were errors for the following fields:</p><ul>';
            foreach ($error as $val) {
                echo "<li>$val</li>";
            }
            echo '</ul>';
        }
        else
        {
            echo '<p>Thank you for contacting ... UK, we will get back to you shortly.</p>';
        }
        ?>
        <table cellpadding="5" cellspacing="0">
        <form method="post" action="">
            <tr>
                <td width="150"><label for="Name">Name: </label></td>
                <td><input type="text" name="Name" value="<?=$name?>" /></td>
            </tr>
            <tr>
                <td><label for="Email">Email: </label></td>
                <td><input type="text" name="Email" value="<?=$email?>" /></td>
            </tr>
            <tr>
                <td><label for="Telephone">Telephone: </label></td>
                <td><input type="text" name="Telephone" value="<?=$telephone?>" /></td>
            </tr>
            <tr>
                <td valign="top"><label for="Message">Message: </label></td>
                <td><textarea name="Message" rows="10" cols="55"><?=$message?></textarea></td>
            </tr>
            <tr>
                <div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div>
            </tr>
            <tr>
                <td></td>
                <td><button type="submit" name="Send">Send Message</button></td>
            </tr>
        </form>
        </table>
    </div>
<?php include ('includes/footer.php'); ?>
</div>
</body>
</html>

What I need it to do is check that the fields are correct and the ReCapture has been verified and when the user clicks submit an email is sent.

This is how I do it, in a working fashion. First of all, my page which displays the recaptcha. I don't have any form fields as I don't need them for this application, but you could easily add them:

<?php
$mailid = $_GET['mailid']; // which email address is needed?
?>

<html>
  <head>
    <title>My test contact verification</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin="anonymous"></script>
  </head>
  <body>
  <h1>Please confirm you are not a robot</h1>
    <form action="?" method="POST">
      <input type="hidden" name="mailid" id="mailid" value="<?php echo $mailid;?>">

      <div class="g-recaptcha" data-sitekey="my-site-key" data-callback="cbtest"></div>
      <br/>
    </form>
    <br />
    <br />
    <div id="result"></div>

    <script type="text/javascript">
    function cbtest(response) {
    // now, send the response to be verified
    var dispdiv = document.getElementById("result");
    dispdiv.innerHTML = "<p>Retrieving the contact details</p>";
    var contact = document.getElementById("mailid");
    var contactsel = contact.value;
    $.ajax({
    url: "http://www.example.com/recaptcha_verify.php",
    type: "POST",
    data: {source: contactsel, response: response},
      }).done(function(data, status, xhr) {
      var ver = data.substring(0,2);
      if (ver == "no") {
      dispdiv.innerHTML = "<p>Sorry, there was a verification problem.</p>";
      } else if (ver == "OK") { 
      var out = data.substring(3);
      dispdiv.innerHTML = "<p>The contact details you requested are:<br />" + out + "</p>";
      } // end of verification response check
      })
      };

    </script>
  </body>
</html>

and my verification code

<?php
if (isset($_POST['response'])) { 
$response = $_POST['response']; }
else {
        echo "no1";
    exit;
}

if (isset($_POST['source'])) {
$source = $_POST['source']; }
else {
    echo "no2";
    exit;
}

$url = "https://www.google.com/recaptcha/api/siteverify";

$secret = "my-secret";

$emails = array(
   "hidden email 1",
   "hidden email 2",
   "hidden email 3");

// is the source reference a valid one?

if ($source < 0 || $source > count($emails)) {
echo "no";
exit;
}

// create the output

 $url = $url."?secret=".$secret. "&response=".$response;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, TRUE); 
        $curlData = curl_exec($curl);

        curl_close($curl);

$out = $emails[$source]; 

// send the response to the verifier

   $captcha_success = json_decode($curlData, TRUE);


   if ($captcha_success['success'] == false) {
       echo "noF";
   }
   else if ($captcha_success['success'] == true) {
       echo "OK|" . $out;
   }

?>

(I've trimmed what I think was spurious code out of the above, hopefully I haven't taken too much out).

I present the user with a screen that just has text and a recaptcha, the incoming variable is passed through to tell my code which hidden email address is needed, obviously you'll add your form fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM