PC & IT SUPPORT MADE EASY FORUM
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Integrate Google reCAPTCHA v3 in HTML Form with PHP

Go down

Integrate Google reCAPTCHA v3 in HTML Form with PHP Empty Integrate Google reCAPTCHA v3 in HTML Form with PHP

Post by jamied_uk 28th October 2022, 11:38

codexworld.com/integrate-google-recaptcha-v3-in-html-form-with-php




Code:

Add reCAPTCHA v3 in the HTML Form

The reCAPTCHA v3 does not interrupt the user and the widget is added to the bottom-right corner of the web page. So, you can bind reCAPTCHA v3 to any action and run it whenever you want.
First, load the reCAPTCHA API JavaScript library.
Code:
<script src="https://www.google.com/recaptcha/api.js"></script>

Define a callback function to handle the reCAPTCHA token submission using JavaScript.
Code:


<script>
function onSubmit(token) {
    document.getElementById("contactForm").submit();
}
</script>


Add predefined attributes to the HTML button, so that reCAPTCHA API will bind the challenge automatically to this button.
  • Specify the Site Key of the reCAPTCHA v3 in the
    Code:
    data-sitekey
    attribute.
  • Specify the JavaScript callback function in the
    Code:
    data-callback


Code:
attribute.
<button class="g-recaptcha"
    data-sitekey="reCAPTCHA_Site_Key"
    data-callback='onSubmit'
    data-action='submit'>Submit</button>


Here is the HTML code example to integrate reCAPTCHA v3 to form.
  • The reCAPTCHA challenge will bind to the submit button.
  • The response token will submit to the server-side script for verification.

Code:

<form id="contactForm" method="post" action="">
    <!-- Form fields -->
    <div class="input-group">
        <input type="text" name="name" value="" placeholder="Your name">
    </div>
    <div class="input-group">   
        <input type="email" name="email" value="" placeholder="Your email">
    </div>
    <div class="input-group">
        <textarea name="message" placeholder="Type message..."></textarea>
    </div>

    <input type="hidden" name="submit_frm" value="1">
   
    <!-- Submit button with reCAPTCHA trigger -->
    <button class="g-recaptcha"
        data-sitekey="Your_reCAPTCHA_Site_Key"
        data-callback='onSubmit'
        data-action='submit'>Submit</button>
</form>


Verify reCAPTCHA Response with PHP

After the form submission, the reCAPTCHA challenge will be submitted to the application’s backend to verify the user’s response and process the contact request.
  • Validate form input fields to check whether the user fills in the correct values.
  • Use
    Code:
    g-recaptcha-response
    POST parameter to get the user’s response token from the client-side script.
  • Execute a cURL request to verify the response token with reCAPTCHA API using PHP.
  • Pass the Site Secret Key (
    Code:
    secret
    ), response token (
    Code:
    response
    ), and user’s IP (
    Code:
    remoteip


Code:
) in POST parameters.If the reCAPTCHA response is valid and successful, process the
contact form submission request further. Otherwise, display an error
notification to the user.
<?php 
 
// Google reCAPTCHA API keys settings 
$secretKey     = 'Your_reCaptcha_Secret_Key'; 
 
// Email settings 
$recipientEmail = 'admin@example.com'; 
 
// Assign default values
$postData = $valErr = $statusMsg = '';
$status = 'error';
 
// If the form is submitted
if(isset($_POST['submit_frm'])){ 
    // Retrieve value from the form input fields
    $postData = $_POST; 
    $name = trim($_POST['name']); 
    $email = trim($_POST['email']); 
    $message = trim($_POST['message']); 
 
    // Validate input fields 
    if(empty($name)){ 
        $valErr .= 'Please enter your name.<br/>'; 
    } 
    if(empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false){ 
        $valErr .= 'Please enter a valid email.<br/>'; 
    } 
    if(empty($message)){ 
        $valErr .= 'Please enter message.<br/>'; 
    } 
 
    // Check whether submitted input data is valid 
    if(empty($valErr)){ 
        // Validate reCAPTCHA response 
        if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ 
 
            // Google reCAPTCHA verification API Request 
            $api_url = 'https://www.google.com/recaptcha/api/siteverify'; 
            $resq_data = array( 
                'secret' => $secretKey, 
                'response' => $_POST['g-recaptcha-response'], 
                'remoteip' => $_SERVER['REMOTE_ADDR'] 
            ); 
 
            $curlConfig = array( 
                CURLOPT_URL => $api_url, 
                CURLOPT_POST => true, 
                CURLOPT_RETURNTRANSFER => true, 
                CURLOPT_POSTFIELDS => $resq_data 
            ); 
 
            $ch = curl_init(); 
            curl_setopt_array($ch, $curlConfig); 
            $response = curl_exec($ch); 
            curl_close($ch); 
 
            // Decode JSON data of API response in array 
            $responseData = json_decode($response); 
 
            // If the reCAPTCHA API response is valid 
            if($responseData->success){
                // Send email notification to the site admin 
                $to = $recipientEmail; 
                $subject = 'New Contact Request Submitted'; 
                $htmlContent = " 
                    <h4>Contact request details</h4> 
                    <p><b>Name: </b>".$name."</p> 
                    <p><b>Email: </b>".$email."</p> 
                    <p><b>Message: </b>".$message."</p> 
                "; 
                 
                // Always set content-type when sending HTML email 
                $headers = "MIME-Version: 1.0" . "\r\n"; 
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
                // Sender info header 
                $headers .= 'From:'.$name.' <'.$email.'>' . "\r\n"; 
                 
                // Send email 
                @mail($to, $subject, $htmlContent, $headers); 
                 
                $status = 'success'; 
                $statusMsg = 'Thank you! Your contact request has been submitted successfully.'; 
                $postData = ''; 
            }else{ 
                $statusMsg = 'The reCAPTCHA verification failed, please try again.'; 
            } 
        }else{ 
            $statusMsg = 'Something went wrong, please try again.'; 
        } 
    }else{ 
        $valErr = !empty($valErr)?'<br/>'.trim($valErr, '<br/>'):''; 
        $statusMsg = 'Please fill all the mandatory fields:'.$valErr; 
    } 

 
?>

Use the following code in the HTML form to display the form submission status message at the client-side script.

<?php if(!empty($statusMsg)){ ?>
    <p class="status-msg <?php echo $status; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
jamied_uk
jamied_uk
Admin

Posts : 2951
Join date : 2010-05-09
Age : 41
Location : UK

https://jnet.sytes.net

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum