• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Help with Implementing Recaptcha? (HTML, PHP)

renzorthered

New Coder
Hi guys. I'm trying to set up a Recaptcha V3 challenge on an html contact form, but I don't know enough about PHP to add to the corresponding PHP form to only proceed with the required fields check and email submission if Recaptcha passes. Can anyone tell me where in my existing code to confirm a successful recaptcha, and what to put in there? The clientside stuff is so simple, but the serverside is Greek to me. Or if there's an easier way that doesn't even involve the PHP?

Trying to alter the PHP to effectively say "If Recaptcha challenge fails or equals zero (or whatever), then say that there was an error and go back." is stumping me. And I suppose I must put something in with the serverside (secret) key to make it work. Don't know.




The HTML Form:
HTML:
<form name="contactform" method="post" action="(website url)/test_form.php">
<center><font size="+1"><strong>Contact us for a FREE ESTIMATE</strong> or with any Questions / Comments</font>
<table width="650" border="5" bordercolor="#333333" cellspacing="5" bgcolor="#003366" cellpadding="5">
  <tr>
    <td width="120" bgcolor="#FFFFFF"><label for="first_name">First Name * </label></td>
    <td width="150"><input  type="text" name="first_name" maxlength="100" size="26"></td>
    <td width="120" bgcolor="#FFFFFF"><label for="last_name">Last Name * </label></td>
    <td width="150"><input  type="text" name="last_name" maxlength="100" size="26"></td>
  </tr>
  <tr>
    <td width="120" bgcolor="#FFFFFF"><label for="telephone">Phone number * </label></td>
    <td width="150"><input  type="text" name="telephone" maxlength="100" size="26"></td>
    <td width="120" bgcolor="#FFFFFF"><label for="altphone">Alternative Phone </label></td>
    <td width="150"><input  type="text" name="altphone" maxlength="100" size="26"></td>
  </tr>
  <tr>
    <td width="120" bgcolor="#FFFFFF"><label for="email">Email * </label></td>
    <td width="150"><input  type="text" name="email" maxlength="200" size="26"></td>
    <td width="120" bgcolor="#FFFFFF"><label for="besttime">Best time to call? </label></td>
    <td width="150"><input  type="text" name="besttime" maxlength="100" size="26"></td>
  </tr>
  <tr>
    <td colspan="4" bgcolor="#FFFFFF"><center><label for="comments">Your message. If asking about a free estimate, <br />please tell us about what sort of exterior services you're looking for *</label></center></td></tr>
    <tr><td colspan="4" bgcolor="#FFFFFF"><center><textarea  name="comments" maxlength="2000" cols="90" rows="6"></textarea></center></td>
  </tr>
  <tr>
    <td colspan="4"><center>
    <button class="g-recaptcha"
        data-sitekey="(client side key)"
        data-callback='onSubmit'
        data-action='submit'>Submit Your Message</button>
    <!--div class="g-recaptcha" data-sitekey="(client side key)"></div-->
    <!--input name="submit" type="submit" value="Submit Your Message" /--></center></td>
  </tr>
</table></center>
</form>





The PHP File (Don't know where to put a challenge success confirmation or what to insert.)
PHP:
<?php

if(isset($_POST['email'])) {
   
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "(my email address)";
    $email_subject = "** Test FORM - Customer Contact";

   
    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please GO 'BACK' and fix these errors.<br /><br />";
        die();
    }
   
    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');    
    }
   
    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required
   
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
  }
  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.<br />';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below.\n\n";
   
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
   
    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Alt Telephone: ".clean_string($altphone)."\n";
    $email_message .= "Best Time to Call: ".clean_string($besttime)."\n";
    $email_message .= "Message: ".clean_string($comments)."\n";
   
   
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

/* Redirect browser */

?>
 
<!-- include your own success html here -->
 
<center>
(The 'thanks for contacting' code I have)
</center>
 
<?php
}
?>
 
Last edited:
Anybody? I just need to add the recaptcha verification to the PHP file in a way that it will need a successful recaptcha and no problems with the inputs to proceed with sending the email.
 
Hey There i am actually adding v3 into a database of mine :) ,
To integrate Google reCAPTCHA v3 into your PHP code, you need to make a post request from your server to Google's server to verify the user's response.

Here's a step-by-step guide to integrate reCAPTCHA v3 into your form:

  1. HTML side: You've added the reCAPTCHA button. Make sure to include the reCAPTCHA JavaScript library just before the closing </head> tag of your HTML:


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

  1. PHP side:
  • After your form is submitted, but before you validate any of the data or send an email, you'll want to verify the reCAPTCHA response.
  • To do this, you'll make a POST request to Google's reCAPTCHA API endpoint, sending them the user's response (from your form post) and your secret key.
  • Google will reply with a JSON object. You'll need to check the "success" field in the object to see if the reCAPTCHA verification passed or failed.
Here's the PHP code to integrate reCAPTCHA v3:


PHP:
// Place this right at the top of your PHP script
if(isset($_POST['g-recaptcha-response'])) {
    $captchaResponse = $_POST['g-recaptcha-response'];
    $secretKey = "YOUR_SECRET_KEY"; // Replace with your secret key
    $verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$captchaResponse");
    $responseData = json_decode($verifyResponse);

    // Check if reCAPTCHA verification failed
    if(!$responseData->success) {
        died('reCAPTCHA verification failed. Please try again.');
    }
    // Optionally you can also check the score if you want to set a threshold
    //if ($responseData->score < 0.5) {
    //    died('reCAPTCHA verification failed. Please try again.');
    //}
}

  1. Integrate the above code into your PHP:
Insert the above PHP code block right at the start of your PHP script, before the if(isset($_POST['email'])) { line.

This will ensure that before any of your own form processing happens, the reCAPTCHA verification takes place. If the verification fails, it will show the error message and stop further execution.

  1. Safety Note:
Remember, never expose your reCAPTCHA secret key in client-side code (like JavaScript or HTML). It should only ever be used server-side.

That's it! Once you've made these changes, your form should now be protected by reCAPTCHA v3.
 
  1. Integrate the above code into your PHP:
Insert the above PHP code block right at the start of your PHP script, before the if(isset($_POST['email'])) { line.

This will ensure that before any of your own form processing happens, the reCAPTCHA verification takes place. If the verification fails, it will show the error message and stop further execution.

So, to add the additional 'if success then move on, else fail' loop to the beginning of the PHP file and that's it? I don't have to encompass all of the message code inside it somehow? It just tries to run the recaptcha 'if statement', then moves on to the message stuff if it succeeds?
 
in a nutshell yes but let's break it down! When you drop in that reCAPTCHA block at the start of your PHP, think of it like a gatekeeper at the entrance of a club. If you don't pass the bouncer (reCAPTCHA in our case), you're not getting in, and the party (your email sending code) won't even know you tried.

But if you pass? Well, then you're in, and the fun begins! The PHP script will continue executing and get to the email processing.

So, in simple terms, slap that reCAPTCHA code right at the beginning. If it's all good, it'll just keep rolling down to your email code. If it fails, it stops right there, throws an error, and won't bother the rest of the code.

No need to wrap your email code inside the reCAPTCHA verification or anything fancy. Just let it run its course, and it'll handle the rest. Give it a shot and let me know how it goes!
 
Thank you, simong!! That's definitely a step in the right direction. Unfortunately, while testing, even though the recaptcha box is operational and we seem to move past it, I'm getting an Internal Server Error.

Implemented code here: Front Range Exterior Services - Colorado Springs Painter and Exteriors Contractor | Replacement Windows and Doors

Internal Server Error​

The server encountered an internal error or misconfiguration and was unable to complete your request.​
Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.​
More information about this error may be available in the server error log.​
 
Last edited:
Thank you, simong!! That's definitely a step in the right direction. Unfortunately, while testing, even though the recaptcha box is operational and we seem to move past it, I'm getting an Internal Server Error.

Implemented code here: Front Range Exterior Services - Colorado Springs Painter and Exteriors Contractor | Replacement Windows and Doors

Internal Server Error​

The server encountered an internal error or misconfiguration and was unable to complete your request.​
Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.​
More information about this error may be available in the server error log.​
Hi there,
So, I don't think it has to do with the recaptcha. I just did a test with the recaptcha, and one without, and both came back with http status code 500. Were you able to actually submit the form properly prior to adding the recaptcha?
 
Top Bottom