Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Add Google reCaptcha V3 Example with PHP

#1
Add Google reCaptcha V3 Example with PHP

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/08/add-google-recaptcha-v3-example-with-php.jpg" width="550" height="413" title="" alt="" /></div><div><div class="modified-on" readability="7.1111111111111"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on August 11th, 2022.</div>
<p>Google reCaptcha V3 is the latest version provided with the highest security in comparison. Google contains different captcha services with reCaptcha V2. There are the (I am not a Robot) checkbox, invisible captcha and etc.</p>
<p>With the V3, Google guarantees zero friction while predicting the score for the website interactions. The score and the response report returned by the reCaptcha V3 is a very good security measure. It helps to take action accordingly to safeguard the website.</p>
<p>Like other Google reCaptcha concepts, the V3 also has more than one method to integrate the captcha challenge. Those are two as listed below.</p>
<ol>
<li>Programmatic invocation of the challenge.</li>
<li>Automatic binding of the challenge with the form button.</li>
</ol>
<p>This article explains to implement both methods by creating examples.</p>
<p>The below diagram will help to have a quick look at the Google reCaptcha V3 process flow.&nbsp; Continue reading to learn how to get the API keys and integrate reCaptcha for your website.</p>
<p>Read also,</p>
<ol>
<li><a href="https://phppot.com/php/php-contact-form-with-google-recaptcha/">PHP Contact Form with Google reCAPTCHA</a>.</li>
<li><a href="https://phppot.com/php/how-to-enable-and-customize-google-invisible-recaptcha-in-a-webpage/">Customize Google Invisible reCAPTCHA on a Webpage</a>.</li>
</ol>
<p>If you prefer <a href="https://phppot.com/php/php-captcha/">custom captcha code using PHP</a>, you may check the linked article for example code.</p>
<p><img loading="lazy" class="alignnone size-large wp-image-18886" src="https://phppot.com/wp-content/uploads/2022/08/google-recaptcha-validation-process-550x413.jpg" alt="google recaptcha validation process" width="550" height="413" srcset="https://phppot.com/wp-content/uploads/2022/08/google-recaptcha-validation-process-550x413.jpg 550w, https://phppot.com/wp-content/uploads/20...00x225.jpg 300w, https://phppot.com/wp-content/uploads/20...68x576.jpg 768w, https://phppot.com/wp-content/uploads/20...rocess.jpg 800w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>How to get Google reCaptcha keys</h2>
<p>This is a two-step simple process to get the API keys to add Google reCaptcha to a website.</p>
<p>These steps are listed below with screenshots.</p>
<ol>
<li>Register your site domain.</li>
<li>Copy the reCaptcha site key and the secret key.</li>
</ol>
<h3>Step1: Register your site domain</h3>
<p>Go to the <a href="https://www.google.com/recaptcha/admin/create" target="_blank" rel="noopener">Google recaptcha admin console</a> to register a domain to integrate reCaptcha V3.</p>
<p>The below screenshot masked the data related to the domain and site owner details. Enter your site details in the place of the masked data.</p>
<p><img loading="lazy" class="alignnone size-large wp-image-18877" src="https://phppot.com/wp-content/uploads/2022/08/register-domain-create-keys-550x764.jpg" alt="register domain create keys" width="550" height="764" srcset="https://phppot.com/wp-content/uploads/2022/08/register-domain-create-keys-550x764.jpg 550w, https://phppot.com/wp-content/uploads/20...16x300.jpg 216w, https://phppot.com/wp-content/uploads/20...e-keys.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h3>Step2: Copy the reCaptcha site key and the secret key.</h3>
<p>Once registration is done, the reCaptcha V3 keys are displayed below. Copy these details and configure them into the website code.</p>
<p>The <strong>site key</strong> is used to render the Google reCaptcha on the client side. And, the <strong>secret key</strong> is used for <a href="https://phppot.com/php/php-form-validation/">server-side verification</a>.</p>
<p>The following example contains an application configuration file for this. Continue reading to know how to configure.</p>
<p><img loading="lazy" class="alignnone size-full wp-image-18878" src="https://phppot.com/wp-content/uploads/2022/08/google-recaptcha-keys.jpg" alt="google recaptcha keys" width="500" height="361" srcset="https://phppot.com/wp-content/uploads/2022/08/google-recaptcha-keys.jpg 500w, https://phppot.com/wp-content/uploads/20...00x217.jpg 300w" sizes="(max-width: 500px) 100vw, 500px"></p>
<h2>About this example</h2>
<p>This example renders the reCaptcha script and element in the landing UI. It has the configuration to make the website reCaptcha ready with the API keys.</p>
<p>It gets the token from the Google reCaptcha API and appends it to the form. On submit, the server-side PHP script receives the token to send the <strong><em>siteverify</em></strong> request to the API.</p>
<p>The reCaptcha API returns a <a href="https://phppot.com/jquery/read-display-json-data-using-jquery-ajax/">JSON response</a> with a score, success boolean, and more details. Based on the score (between 0 to 1), it helps to gauge the interaction’s standard. We have enabled a <a href="https://phppot.com/php/show-php-captcha-on-failed-login-attempts/">custom captcha solution based on the login validity</a> standard.</p>
<p>It integrates the Google reCaptcha V3 programmatic challenge in the root. If you want to implement the “automatic binding” method, then it is in a separate folder.</p>
<p>The below structure shows the reCaptcha example files order and location. It will be helpful to set up this code correctly in a development environment.</p>
<p><img loading="lazy" class="alignnone size-full wp-image-18874" src="https://phppot.com/wp-content/uploads/2022/08/google-recaptcha-php-files.jpg" alt="google recaptcha php files" width="190" height="171"></p>
<h3>Application configuration file</h3>
<p>It configures the Google reCaptcha V3 site and the secret keys used in the examples below.</p>
<p>The site key is used to render the Google recaptcha element on the client side. The secret key is used in the PHP files to build the site verification request parameters.</p>
<p class="code-heading">Config.php</p>
<pre class="prettyprint"><code class="language-php">&lt;?php class Config
{ const GOOGLE_RECAPTCHA_SITE_KEY = ''; const GOOGLE_RECAPTCHA_SECRET_KEY = '';
} ?&gt;
</code></pre>
<h2>Method 1: Programatically invoking Google reCaptcha token via script</h2>
<p>This method is used when the developer wants to have more programming control over the reCaptcha token.</p>
<p>During the explicit execution, it sets parameters to the request. These parameters can be returned with the Google reCaptcha V3 response. This will be helpful for additional verification.</p>
<h3>HTML page renders form with reCaptcha JS</h3>
<p>This landing page loads the JavaScript API while rendering the form UI. It uses the Google reCaptcha site key while loading the JavaScript.</p>
<p class="code-heading">index.php</p>
<pre class="prettyprint"><code class="language-php-template">&lt;?php
require_once __DIR__ . '/Config.php';
?&gt;
&lt;html&gt;
&lt;head&gt;
&lt;link rel="stylesheet" type="text/css" href="css/form.css" /&gt;
&lt;link rel="stylesheet" type="text/css" href="css/style.css" /&gt;
&lt;title&gt;Form with Google reCaptcha V3&lt;/title&gt; &lt;script src="https://www.google.com/recaptcha/api.js?render=&lt;?php echo Config::GOOGLE_RECAPTCHA_SITE_KEY; ?&gt;"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt; &lt;div class="phppot-container tile-container"&gt; &lt;h3 class="text-center"&gt;Google reCaptcha V3&lt;/h3&gt; &lt;form id="frm" name="frm" method="post" onSubmit="getToken(event)"&gt; &lt;div&gt; &lt;div class="row"&gt; &lt;label&gt;Feedback&lt;/label&gt; &lt;input type="text" name="txt_report" class="full-width" required&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;input type="submit" value="Send" class="full-width"&gt; &lt;/div&gt; &lt;div id="ack-message"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3>Execute reCaptcha JavaScript API for token</h3>
<p>It executes the Google reCaptcha request explicitly. The callback function of this action will return the reCaptcha token.</p>
<p>Then, the callback dynamically creates an input element using JavaScript. It loads the token to this element and appends it to the form.</p>
<p>After getting the token field, the <a href="https://phppot.com/jquery/prevent-form-double-submit-using-jquery/">form is submitted via JavaScript</a>. The&nbsp;<em>submitForm</em> function <a href="https://phppot.com/php/ajax-programming-with-php/">posts the form data to the PHP via AJAX</a>. In a previous article, we have seen how to enable <a href="https://phppot.com/jquery/php-captcha-using-jquery-ajax/">PHP custom captcha using AJAX</a>.</p>
<p class="code-heading">index.php (Javascript Google reCaptcha execute)</p>
<pre class="prettyprint"><code class="language-javascript">// Execute Google reCaptcha v3 to get token function getToken(event) { event.preventDefault(); grecaptcha.ready(function() { grecaptcha.execute('&lt;?php echo Config::GOOGLE_RECAPTCHA_SITE_KEY; ?&gt;', { action: 'submit' }).then(function(token) { var button = document.createElement('input'); button.type = 'hidden'; button.name = 'recaptcha_token'; button.id = 'recaptcha_token'; button.value = token; var form = document.getElementById("frm"); form.appendChild(button); submitForm(); });; });
} // Submit reCaptcha token to the PHP
function submitForm() { const form = document.getElementById('frm'); const formData = new FormData(form); var xhttp = new XMLHttpRequest(); xhttp.open('POST', 'form-action.php', true); xhttp.send(formData); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 &amp;&amp; xhttp.status == 200) { document.getElementById("ack-message").innerHTML = xhttp.responseText; document.getElementById('recaptcha_token').remove(); } }
}
</code></pre>
<h3>Verify website interaction using Google reCaptcha V3 API</h3>
<p>The form submits action calls this PHP script by sending the reCaptcha token. It builds the post parameters with the Google reCaptcha v3 secret key and token.</p>
<p>This <a href="https://phppot.com/php/php-curl-post/">PHP script uses cURL to post the request</a> to the reCaptcha API. The cUrl response returns the JSON&nbsp; data as given by the Google API.</p>
<p>It returns the score about the interaction made on the website. This score will be between 0.0 (lower) and 1.1(higher) ranking. It helps to predict the necessary steps to make to protect the site.</p>
<p class="code-heading">form-action.php</p>
<pre class="prettyprint"><code class="language-php">//PHP reCaptcha validation
&lt;?php
require_once __DIR__ . '/Config.php'; $reCaptchaToken = $_POST['recaptcha_token'];
$postArray = array( 'secret' =&gt; Config::GOOGLE_RECAPTCHA_SECRET_KEY, 'response' =&gt; $reCaptchaToken
); $postJSON = http_build_query($postArray); $curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postJSON);
$response = curl_exec($curl);
curl_close($curl);
$curlResponseArray = json_decode($response, true); if ($curlResponseArray["success"] == true &amp;&amp; ! empty($curlResponseArray["action"]) &amp;&amp; $curlResponseArray["score"] &gt;= 0.5) { mail("[email protected]", "New report", $_POST["txt_report"]); $output = "&lt;div id='phppot-message' class='success'&gt;Feedback received.&lt;/div&gt;";
} else { $output = "&lt;div id='phppot-message' class='error'&gt;Invalid request.&lt;/div&gt;";
}
print $output;
exit();
</code></pre>
<h2>Method 2: Automatic binding callback with the submit button</h2>
<p>This is a basic and simple method of integrating Google reCaptcha V3 for a site. In this automatic binding of the reCaptcha challenge, it gets the token in the callback.</p>
<h3>Site HTML to bind the reCaptcha challenge automatically</h3>
<p>It loads the Google reCaptcha JavaScript API as we did in method 1.</p>
<p>The <code class="language-php-template">g-recaptcha</code> field binds the callback, action, and reCaptcha site key with the HTML5 data attributes.</p>
<p class="code-heading">&nbsp;automatic-binding/index.php</p>
<pre class="prettyprint"><code class="language-php-template">&lt;?php
session_start();
require_once __DIR__ . '/../Config.php';
?&gt;
&lt;html&gt;
&lt;head&gt;
&lt;link rel="stylesheet" type="text/css" href="./../css/form.css" /&gt;
&lt;link rel="stylesheet" type="text/css" href="./../css/style.css" /&gt;
&lt;title&gt;Form with Google reCaptcha V3&lt;/title&gt; &lt;script src="https://www.google.com/recaptcha/api.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt; &lt;div class="phppot-container tile-container"&gt; &lt;h3 class="text-center"&gt;Google reCaptcha Automatic Binding&lt;/h3&gt; &lt;form id="frm" name="frm" method="post" action="action.php"&gt; &lt;div&gt; &lt;div class="row"&gt; &lt;label&gt;Feedback&lt;/label&gt; &lt;input type="text" name="txt_report" class="full-width" required&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;input type="button" class="g-recaptcha full-width" data-sitekey="&lt;?php echo Config::GOOGLE_RECAPTCHA_SITE_KEY; ?&gt;" data-callback='onSubmit' data-action='submit' value="Send" /&gt; &lt;/div&gt; &lt;?php if (! empty($_SESSION["ack_message"])) { ?&gt; &lt;div id="ack-message"&gt;&lt;?php echo $_SESSION["ack_message"]; ?&gt;&lt;/div&gt; &lt;?php } $_SESSION["ack_message"] = ""; ?&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3>JavaScript callback to append token field to the form</h3>
<p>This callback function is linked with the Google reCaptcha element, which is the send button of the form. So, on clicking the send button, it calls the <em>onSubmit</em> JavaScript function.</p>
<p>This callback has the reCaptcha token to be appended to the form data.</p>
<p class="code-heading">automatic-binding/index.php (JavaScript callback)</p>
<pre class="prettyprint"><code class="language-javascript">// JavaScript
function onSubmit(token) { var button = document.createElement('input'); button.type = 'hidden'; button.name = 'recaptcha_token'; button.value = token; var form = document.getElementById("frm"); form.appendChild(button); form.submit();
}
</code></pre>
<h3>PHP action to predict Google reCaptcha score</h3>
<p>In PHP, it verifies the site and checks the interaction score. It contains the same code as the <em>form-action.php</em> we used in method 1.</p>
<p>The difference is that the response is sent via session instead of printing it to <a href="https://phppot.com/php/php-mysql-inline-editing-using-jquery-ajax/">AJAX callback</a>.</p>
<p class="code-heading">automatic-binding/action.php</p>
<pre class="prettyprint"><code class="language-php">//Google reCaptcha V3 server-side verification
&lt;?php
require_once __DIR__ . '/Config.php'; $reCaptchaToken = $_POST['recaptcha_token']; $postArray = array( 'secret' =&gt; Config::GOOGLE_RECAPTCHA_SECRET_KEY, 'response' =&gt; $reCaptchaToken
); $postJSON = http_build_query($postArray); $curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postJSON);
$response = curl_exec($curl);
curl_close($curl); $curlResponseArray = json_decode($response, true); if ($curlResponseArray["success"] == true &amp;&amp; $curlResponseArray["score"] &gt;= 0.5) { mail("[email protected]", "New report", $_POST["txt_report"]); $output = "&lt;div id='phppot-message' class='success'&gt;Feedback received.&lt;/div&gt;";
} else { $output = "&lt;div id='phppot-message' class='error'&gt;Invalid request.&lt;/div&gt;";
} $_SESSION["ack_message"] = $output;
header("Location: automatic-binding.php");
?&gt;
</code></pre>
<p><a class="download" href="https://phppot.com/downloads/google-recaptcha-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/google-recaptcha-v3-php/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/08/...-with-php/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016