I spent a day getting Recaptcha to work on a site I created. We had to move the site to another hosting company recently. Now it constantly fails when the form is submitted.
I created a new set of keys and still nothing. I can't find any definitive support for this issue.
Could it be a PHP or server setting?
Any help would be greatly appreciated. Even if it's just a way to get some data upon failure.
I'm using a demo form I found for testing purposes. It's the second demo I've tried and they both failed on submission.
The Form
<html>
<head>
<title>Google recapcha demo - Codeforgeek</title>
<script src='https://www.google.com/recaptcha/api.js' async defer></script>
</head>
<body>
<h1>Google reCAPTHA Demo</h1>
<form action="captcha-php.php" method="post" enctype="multipart/form-data">
<input name="sender_name" placeholder="Your Name..."/>
<input name="sender_email" placeholder="Your email..."/>
<textarea placeholder="Your Message..." name="sender_message"></textarea>
<div class="captcha_wrapper">
<div class="g-recaptcha" data-sitekey="6LdMl0saAAAAAI4PyxOt24481BPzmzTmiU2GGhR6"></div>
</div>
<button type="submit" id="send_message">Send Message!</button>
</form>
</body>
</html>
captcha-php.php
<?php
$sender_name = stripslashes($_POST["sender_name"]);
$sender_email = stripslashes($_POST["sender_email"]);
$sender_message = stripslashes($_POST["sender_message"]);
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => 'I have entered the secret key here',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<p>You are a bot! Go away!</p>";
} else if ($captcha_success->success==true) {
echo "<p>You are not not a bot!</p>";
}
?>
Related
I moved my website and domain to a new hoster and since then Google Recaptcha has stopped working.
I haven't changed anything in the code and the domain has also remained the same.
This is my PHP code to check the verification it has worked for years
<?php
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '************************',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo '{ "alert": "error", "message": "<strong>Captcha Check Fail</strong> Bitte versuche es nocheinmal." }';
} else if ($captcha_success->success==true) {
}
?>
this is a finished script from the internet, but it doesn't work either. I've tried several finished scripts but none of them work
<script src="https://google.com/recaptcha/api.js" async defer></script>
<form action="" method="POST" style="width: 80%; margin-left: 497px;">
<div style="margin-left: 48px;"><b> Registration Form </b><br><br></div>
<div>Name: <input type="text" name="name" value="" /><br><br></div>
<div>Email: <input type="text" name="email" value="" /><br><br></div>
<div class="g-recaptcha" data-sitekey="******************"></div><br><br>
<input type="submit" name="submit" value="SUBMIT">
</form>
<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'SUBMIT'){
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$secret = '*********************';
$verifyResponse = file_get_contents('https://google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->true)
{ ?>
<div style="color: limegreen;"><b>Your contact request have submitted successfully.</b></div>
<?php }
else
{?>
<div style="color: red;"><b>Robot verification failed, please try again.</b></div>
<?php }
}else{?>
<div style="color: red;"><b>Please do the robot verification.</b></div>
<?php }
}
?>
Of course I have deleted the Recaptcha account several times and generated new tokens, but nothing changes. can it also be due to the hoster? are there any PHP settings that prevent recapatcha? the server runs on PHP 7.4 and the domain has an SSL certificate from lets encrypt.
thank you for your help
Adding as an answer here for anyone else seeking similar advice.
The issue was that the new host didn't have allow_url_fopen enabled in the PHP configuration.
This can be checked by searching the output of a phpinfo(); call.
Enabling allow_url_fopen can usually be achieved by editing your php.ini file, making changes in php settings in cPanel or Plesk or by contacting your hosting provider's support team.
file_get_contents requires allow_url_fopen.
Please excuse the poor title.
I am a total beginner and don't know the right terms to make it better.
I am trying to POST form data using PHP.
My problem is that before i POST the form data i need to get a value from the form, that is changing each time i request the page.
Please notice the second input, the value is auto generated and is a random number each time i request the form.
Here is my form.php:
<?php
if(!isset($_REQUEST['submit_btn'])){
echo '
<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<input type="text" name="user_name" id="user_name">
<input type="hidden" name="a_random_password" value="'.(rand(10,100)).'">
<input type="submit" value="submit" name="submit_btn">
</form>';
}
if(isset($_REQUEST['submit_btn']))
{
$user_name= $_POST["user_name"];
$a_random_password = $_POST["a_random_password"];
echo "Your User Name is:". $user_name;
echo "<br> and your Password is : $a_random_password;
}
?>
And my post.php
<?php
$url = "http://test.com/form.php";
$data = array(
'user_name' => 'John',
'a_random_password' => 'xxx',
'submit' => 'submit'
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Error"; }
var_dump($result);
?>
So how do i get the a_random_password value and submit it along with the form in a single request, else the password wont fit with the user name.
Sup, what you wanna do is impossible using PHP in that way, cause the only job PHP has is to render your content on server side. To listen to the client side you'll need to use javascript.
let randomPassword = document.getElementById('a_randow_password')
let name = document.getElementById('name')
let password = document.getElementById('password')
name.onkeyup = function(){
password.value = randomPassword.value + name.value
}
<input type="text" id="name" name="user_name" placeholder="name"><br />
<input type="hidden" name="a_random_password" id="a_randow_password" value="xxx">
<input type="text" id="password" placeholder="password"><br />
Not sure exactly what you trying to achieve, but if You want to interrupt a request (and modify|use it) from HTML to PHP, You need AJAX request (JavaScript).
So, I'm trying to implement to some website the brand new Invisible reCaptcha by Google.
I am following the steps exactly but it continously gives me missing-input-reponse error.
HTML Code:
<form id="subscribe-form" class="form-inline" action="phpScripts/subscribe/subscribeHandler.php" method="post">
<div class="input-group">
<input type="email" name="email" class="form-control" size="50" placeholder="Email Address" required>
<div class="input-group-btn">
<button class="g-recaptcha btn btn-danger" data-sitekey="6LfoNhkUAAAAAEcQFx8vGHZKHXsZ_q0j2KDnmU9M" data-callback="submitForm">Subscribe</button>
</div>
</div>
</form>
PHP Code:
<?php
include 'databaseConnection.php';
if($_POST){
$secret = "MY SECRET KEY";
$captcha= $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$url= file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip");
print_r($url);
$decodedResponse = json_decode($url, TRUE);
if($decodedResponse['success'] == 1){//code here}
So, I'm thinking that my $captcha variable cannot "catch" nothing from the POST of g-recaptcha-response. But why, this is exactly how Google says and exactly as the old reCaptcha v2.
Aswell, i have included <script src='https://www.google.com/recaptcha/api.js'></script>
I was facing the same problem for several hours, until I finally understood the logic behind this "invisible-captcha" !
the reason you don't get a response is simply because there is an empty textarea element with an id and name of g-recaptcha-response
this textarea only populates with the response string after the challenge has been completed (which happens normally in the usual recaptcha), but for "invisible-captcha" you must explicitly call grecaptcha.execute(); with your "submit" button, after which the textarea is populated, and your form is automatically submitted (assuming you have bound the submission with your callback function).
In my case, I already have php handling the form and recaptcha validation, so I decided to stick with the old "checkbox" version (at least until it gets improved), because I realized it will be really annoying to change everything (form submission logic, button action and JavaScript code) just to hide a checkbox! especially that both methods are nearly the same !
The issue could be that you're tying the functionality to a button possibly.
Try implementing the code they give you when creating your keys:
<form id="subscribe-form" class="form-inline" action="phpScripts/subscribe/subscribeHandler.php" method="post">
<div class="input-group">
<input type="email" name="email" class="form-control" size="50" placeholder="Email Address" required>
<div class="g-recaptcha" data-sitekey="{keyhere}"></div>
<div class="input-group-btn">
<button class="btn btn-danger" data-sitekey=" data-callback="submitForm">Subscribe</button>
</div>
</div>
</form>
For the PHP logic validation:
if ( $_POST['g-recaptcha-response'] ) {
$secret = '{keyhere}';
$response = file_get_contents( "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $_POST['g-recaptcha-response'] . "&remoteip=" . $_SERVER['REMOTE_ADDR'] );
$response = json_decode( $response );
if ( ! $response->success ) {
//return error
}
//code logic below
}
The div code provided when creating the keys should properly generate all of the HTML from their end to be able to processed by your PHP validation when submitting your form.
Here is a solution.
Client Side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>reCaptcha</title>
<!--api link-->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<!--call back function-->
<script>
function onSubmit(token) {
document.getElementById('reCaptchaForm').submit();
}
</script>
</head>
<body>
<div class="container">
<form id="reCaptchaForm" action="signup.php" method="POST">
<input type="text" placeholder="type anything">
<!--Invisible reCaptcha configuration-->
<button class="g-recaptcha" data-sitekey="<your site key>" data-callback='onSubmit'>Submit</button>
<br/>
</form>
</div>
</body>
</html>
Server Side validation: Create a signup.php file
<?php
//only run when form is submitted
if(isset($_POST['g-recaptcha-response'])) {
$secretKey = '<your secret key>';
$response = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp");
$result = json_decode($reCaptchaValidationUrl, TRUE);
//get response along side with all results
print_r($result);
if($result['success'] == 1) {
//True - What happens when user is verified
$userMessage = '<div>Success: you\'ve made it :)</div>';
} else {
//False - What happens when user is not verified
$userMessage = '<div>Fail: please try again :(</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>reCAPTCHA Response</title>
</head>
<body>
<?php
if(!empty($userMessage)) {
echo $userMessage;
}
?>
</body>
</html>
Use grecaptcha.reset() to reset the recaptcha after each execution and all should work just fine. Follow this link for more info on grecaptcha.reset().
I am trying to implement Google's reCaptcha v.2.0 but i am getting null in g-recaptcha-response due to this reCaptcha is not working properly and I am always getting the error that Please click on the reCAPTCHA box. even if I successfully submitted the Captcha. I var_dump the $_POST['g-recaptcha-response'] and I am getting null. Please help me. Below is my code.
HTML
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<form action="" method="POST">
<div class="g-recaptcha" style="margin-left: 230px; margin-top: 40px;" data-sitekey="MySiteKey"></div>
</form>
PHP
if (isset($_POST['submit'])) {
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
//your site secret key
$secret = 'My Site Secret Key';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if ($responseData->success) {
// My All Logic Here
} else {
$error[] = 'Robot verification failed, please try again.';
}
} else {
$error[] = 'Please click on the reCAPTCHA box.';
}
}
I am always getting the error Please click on the reCAPTCHA box. on successful submission too. Please help me. Thanks in advance.
Note:- There is no table tag used in between the Form.
I've run into the same issue. The strangest part is a client-side call to grecaptcha.getResponse() returns to correct response. For some reason it's just not setting g-recaptcha-response.
So my workaround was to set a data-callback function to populate a hidden field with the response and use that server-side instead. The hidden input also helps with ease of client-side validation.
eg:
<div class="g-recaptcha" data-callback="captcha_onclick" data-sitekey="######"></div>
<input type="hidden" name="recaptcha" id="recaptchaValidator" />
javascript:
function captcha_onclick() {
document.getElementById('recaptchaValidator').value = grecaptcha.getResponse();
}
server-side:
if(!empty($_POST['recaptcha'])) {
$captcha = $_POST['recaptcha'];
...
}
I'm not sure how you're submitting the form without an actual submit button, but I've copy/pasted your code and it works for me. I did change the error arrays into echo to display the else messages.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form action="" method="POST">
<div class="g-recaptcha" style="margin-left: 230px; margin-top: 40px;" data-sitekey="Your-Public-Site-Key"></div>
<input type="submit" name="submit" value="Post comment">
</form>
</body>
</html>
<?php
if( isset($_POST['submit']) ) {
if( isset($_POST['g-recaptcha-response']) && !empty( $_POST['g-recaptcha-response'] ) ) {
//your site secret key
$secret = 'Your-Private-Site-Key';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success) {
// My All Logic Here
echo 'Success Message';
}
else {
echo 'Robot verification failed, please try again.';
}
}
else {
echo 'Please click on the reCAPTCHA box.';
}
}
?>
EDIT: I'm using reCaptcha 2.0, should I not be using recaptchalib.php?
Live DEMO
http://josiahbertoli.com/
I'm getting the following error when I submit a form (ignore the blank values for the input fields)(with debug code):
Error
_POST: =========
Array
(
[first_name] =>
[last_name] =>
[email] =>
[subject] =>
[comments] =>
[g-recaptcha-response] => big-long-value
)
=========
The reCAPTCHA wasn't entered correctly. Go back and try it again.(reCAPTCHA said: )`
How my webpage is set up:
HTML
<form id="query-form" action="wp-content/themes/portfolio/submit-form.php" method="post" name="myForm">
<input id="first_name" name="first_name" size="35" type="text" placeholder="e.g. John" />
<input id="last_name" name="last_name" size="35" type="text" placeholder="e.g. Smith" />
<input id="email" name="email" size="35" type="text" placeholder="e.g. example#domain.com" />
<input id="subject" name="subject" size="35" type="text" placeholder="e.g. Feedback" />
<textarea id="comments" name="comments"></textarea>
<div class="g-recaptcha" data-sitekey="6Le8WxcTAAAAAGqymotU9wtOBFEmWgjM3j2kqTcB"></div>
<input type="submit" value="Submit" />
</form>
Submit uses method POST to call the action submit-form.php which is as follows
PHP
<?php
require_once('recaptchalib.php');
$privatekey = "the-key-that-i-put-in";
echo "<pre> _POST: =========\n"; print_r($_POST); echo "\n=========\n</pre>";
$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$resp = null;
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); }
else {
// Your code here to handle a successful verification
include '../../../../process.php';
}
?>
Thank you for your responses, I appreciate it.
For displaying the reCAPTCHA widget you don't need any library file, you just have to include the necessary JavaScript resource, like this:
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Here's the reference:
Displaying the widget
Now comes to your user's response. Since you're using Google reCAPTCHA V2, you should fetch the user's response using the POST parameter g-recaptcha-response.
Here's the reference:
Verifying the user's response
So your code should be like this:
<?php
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$privatekey = "YOUR_PRIVATE_KEY";
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$privatekey."&response=".$_POST['g-recaptcha-response'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
echo "success";
}else{
// failure
echo "failure";
}
}else{
// user didn't enter reCAPTCHA
echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.";
}
?>