I am running a Wordpress site and want to protect a custom contact form with Googles reCaptcha v3. Sadly my code seems to be wrong and I couldnt find the problem, please help.
This is my Form
<?php
// reCAPTCHA v3
define('SITE_KEY', 'Key');
define('SECRET_KEY', 'SCRT_KEY');
echo '<script src="https://www.google.com/recaptcha/api.js?render=' . SITE_KEY . '"></script>';
?>
<form action="<?php echo get_home_url(); ?>/sent" method="POST" id="footer-form">
<!--INPUT FIELDS HERE-->
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
<button class="button_1" type="submit">
Send
</button>
</form>
<script>
grecaptcha.ready(function() {
grecaptcha.execute("KEY IS HERE", {action: "homepage"})
.then(function(token) {
console.log(token);
document.getElementById("g-recaptcha-response").value=token;
});
});
</script>
My form posts to this php file
// reCAPTCHA v3
define('SITE_KEY', 'KEY');
define('SECRET_KEY', 'SCRT_KEY');
$Response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".SECRET_KEY."&response={$_POST['g-recaptcha-response']}");
$Return = json_decode($Response);
if($Return->success == true && $Return->score > 0.5){
EMAIL CODE HERE
}
thats about it.. first part seems to work because my g-recaptcha field value got the session token
but the $Response is always false ( i think file_get_contents doesnt work?)
I hope someone can help me, also I dont want to use a PlugIn. Thanks
This code is adapted from this tutorial:
https://youtu.be/61QBrGpwQGg?si=TU3BUsN1RXN9jpmq
This guy had the same problem, but no solution:
The problem was that file_get_contents()
had missing context...
Google Api only accepts POST
requests. Needed stream_context_create()
...