Google ReCaptcha not posting 'g-recaptcha-response' on SOME pages - php

I have been having this issue for a while and I cant figure it out. My Google recaptcha code seems to work on some websites - but the exact same code when added to other websites (or even other pages within the same website) won't work.
When it doesn't work, if I do a var_dump($_POST['g-recaptcha-response']); (on the second page) I get NULL.
My initial/form code:
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="xxxxx"></div>
My verification page code:
$gRecaptcha = $_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=xxxxx&response=".$gRecaptcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false || !$gRecaptcha){
die('xxxx');
}
There are other's that posted this question as well, but it doesn't seem any of them have a solution posted (they all just switched to a different captcha).
Any suggestions what to check next?

Your condition inside if clause is wrong. The API response is a json object, like this:
{
"success": true|false,
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
Here's the reference:
Verifying the user's response
So first you have to decode it using json_decode() function and then check the status of user's response.
Hence your code should be like this:
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//get verified response data
//your site secret key
$secret = 'YOUR_SECRET_KEY';
$gRecaptcha = $_POST['g-recaptcha-response'];
$gRecaptcha = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'];
$response = file_get_contents($gRecaptcha);
$responseData = json_decode($response);
if($responseData->success){
// success
}else{
// failure
}
}

Use like this:
Step 1 :
put this code for validate :
<?php
$secret = "Your own code";
$sitekey = "Your own code";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha){
header("Location: index.php?info=cap");
exit;
}
$response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false)
{
header("Location: index.php?info=cap");
exit;
}
}
?>
Step 2 : use this tag in your form :
<label>I'm not robot: </label>
<div class="g-recaptcha"></div>
Step 3 : Google API
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
<script type="text/javascript">
var CaptchaCallback = function(){
$('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {'sitekey' : '<?php echo $sitekey;?>'});
});
};
</script>

Verify you have added both of these in google recaptcha:
www.yourdomain.com and yourdomain.com

Related

Redirecting to a URL that is sent through an API Response

I'm new in programming and API and I want to know how can I redirect to the URL sent by an API Response like below, please take note that the merchantURL changes everytime a customer submit new transaction.
decision = ACCEPT
reasonCode = 100
requestID = 5199043764236716204011
requestToken = AhjnrwSTGdc55dvfMd/rmBles0iRokq1GiOZKW+XDR/x6Q27g++QyaSZbpAcCSAkxnXOeXb3zHf6wAAAAQqe
apSaleReply->reasonCode = 100
apSaleReply->merchantURL = https://www.sofort.com/payment/go/3e54e5e50b5114f5c11ef40b2d45dbb7a4d808b3
This is how I requested the merchantURL:
printf( "apSaleReply->merchantURL = " . $reply->apSaleReply->merchantURL . "<br>");
and I have an IF statement that if the reason code is equal to 100 then it will redirect to the URL:
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "";
</script>
<?php
}
This is already working if I input any URL, I'm only stuck on how to get the value of the merchantURL since it is always changing and specify it in the window.location.href.
Hope you can help me out! Thank you in advance!
You can use php header
header("Location: " . $reply->apSaleReply->merchantUR );
Or you can alter your existing code as below to get this work
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "<?php echo $reply->apSaleReply->merchantUR; ?>";
</script>
<?php
}
What about this?
window.location.href = "<?= $reply->apSaleReply->merchantURL ?>";
(I assume your template and back-end code is in the same file, otherwise use a session data. Let me know if it's the case.)

Strange thing with Google nocaptcha

I have a strange problem with Google Captcha. I've tried all kinds of php codes from different tutorials, but the result is exactly the same every time...
The problem is this:
it shows up correctly
if you check the box, it works correctly
if you then send the form it works correctly
but... if you don't check the box, the form is still sent!
So, in other words, it's only on the form as a decorative piece. What could be the problem? It's probably something very simple, but I'm totally missing it.
Help or insights are very much appreciated! Thanks in advance!
Addendum
The following is the code that came with the template I used:
require_once('recaptcha-php-1.11/recaptchalib.php');
if ($use_captcha == 1) {
$resp = null;
$error = null;
$reCaptcha = new ReCaptcha($secret);
$secret = "MY SECRET KEY HERE";
$captcha_error_message = '<div class="pi-alert-danger fade in"><button type="button" class="pi-close" data-dismiss="alert"><i class="icon-cancel"></i></button><p>Bewijs dat je geen robot bent!</p></div>';
if (isset($_POST["captcha_response"]) && $_POST["captcha_response"] != '') {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["captcha_response"]
);
if ($resp && $resp->success != true) {
echo $captcha_error_message;
exit();
}
} else {
echo $captcha_error_message;
exit();
}
}
You have to check if the captcha was solved (at your PHP-Script which do anything with the Form-data)
Like this:
function checkCaptcha($recaptchaResponse) {
$recaptchaPrivateKey = 'Your Private Key';
if(! $recaptchaResponse)
return false;
$recaptchaObj = new ReCaptcha($recaptchaPrivateKey);
$response = $recaptchaObj->verifyResponse($_SERVER["REMOTE_ADDR"], $recaptchaResponse);
if($response != null && $response->success)
return true;
return false;
}
If you don't include a function like this to your form function, your server will say, the form is okay, because it don't know about the captcha.
Note, that you have to include the Google-captcha Libarys-File as well. You can find it here:
https://github.com/google/recaptcha/blob/1.0.0/php/recaptchalib.php (Worked for NoCaptcha as well)

JQuery Submit not called with remote verification [duplicate]

I want to validate if username exists in database using jQuery.validate so here's what I have so far:
jQuery:
$("#signupForm").validate({
rules: {
username: {
required: true,
minlength: 3,
remote: "check-username.php"
}
},
messages: {
username:{
remote: "This username is already taken! Try another."
}
}
});
check-username.php:
<?php
require_once "./source/includes/data.php";
header('Content-type: application/json');
$name = mysql_real_escape_string($_POST['username']);
$check_for_username = mysql_query("SELECT username FROM mmh_user_info WHERE username='$name'");
if (mysql_num_rows($check_for_username) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
?>
This code always shows an error that the username is taken even if it's not.
I'm using jQuery Mobile 1.9.1
Thanks in advance.
I've managed to get this to work by changing the PHP technique I was using, here's my PHP:
<?php
require_once "./source/includes/data.php";
header('Content-type: application/json');
$request = $_REQUEST['username'];
$query = mysql_query("SELECT * FROM mmh_user_info WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>
Thanks everyone here for your help :)
I have two resources for to look at.
Official example from the validate plugin:
http://jquery.bassistance.de/validate/demo/milk/
jQuery forum solution:
http://forum.jquery.com/topic/jquery-validation-plugin-remote-validation-problem-locks-up
The possible solution is that the response does not need to be json encoded as far as I can tell. Since json needs key value pairs, suppling just the value won't work. So try to just echo it out as 'true' or 'false' strings.
Second, the validate uses GET for the form submission method, not POST.
NOTE: JUST FOUND POSSIBLE SOLUTION QUESTION
jQuery Remote validation

get the result from mysql+php and shows in titanium

I have developing the one application using titanium.
Here the values are inserted successfully.But i didn't get the success message from webservices code.
I have using following code for insert a databaase :
In titanium side code :
function StaffRegistration(){
if($.staff_firstname.value != "" && $.staff_firstname.value != null){
var request = Ti.Network.createHTTPClient({
onload:alert(this.responseText),
onerror: function(e){
Ti.API.debug(e.error);
alert(this.responseText);
},
timeout:1000,
});
request.open("POST","xxx/xxx.php");
var params = ({"staff_firstname": $.staff_firstname.value,"staff_email": $.staff_email.value,"staff_password": $.staff_password.value,});
request.send(params);
}
else{
alert("Please enter the firstname");
}
Ti.API.info("Result for registration = " + this.responseText);
};
I have using a following php(webservice code) :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$staff_firstname = $data['staff_firstname'];
$staff_email = $data['staff_email'];
$staff_password = md5($data['staff_password']);
include "db_connect.php";
$db = new DB_CONNECT();
$result = mysql_query("SELECT staff_email,staff_firstname from at_staff WHERE staff_email = '$staff_email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while($queryresult=mysql_fetch_array($result)) {
$uname[]=$queryresult['staff_firstname'];
$uemail[]=$queryresult['staff_email'];
}
if(in_array($staff_firstname,$uname) and in_array($staff_email,$uemail)) {
$response='{"Error":"1","Message":"Username and Email already exist"}';
echo $response;
} else if (in_array($staff_firstname,$uname)) {
$response='{"Error":"1","Message":"Username already exist"}';
echo $response;
} else {
$response='{"Error":"1","Message":"Email already exist"}';
echo $response;
}
} else {
$response='{"Error":"1","Message":"Successfully Registered"}';
echo $response;
$data=array("staff_firstname"=>"'".$staff_firstname."'",
"staff_email"=>"'".$staff_email."'",
"staff_password"=>"'".$staff_password."'"
);
echo $response;
}
?>
How can i get the $response in titanium from this webservice url.
#user2218667
Ti.API.info("Result for registration = " + this.responseText);
will NEVER work as you show in the first piece of code .
why ? because you send a request which will take like 1 seconde (for exemple), obviously, your programm won't wait 1 sec after
request.send(params);
i will continue the programm and when the request return a result, it will get into
onload(e) :
and here only you will be able to have your $result.
is this ok? well now, if this.responseData isn't effective, I don't have the solution .Can you check your line : "} else {" ,i supose there is a if above in the code? are you sure $result is defined upper?
Can you try the same request without titanium with a basic html form to be sure $result is write correctly in this case, like this, we will know if the problem come from php or from the link betwin php & titanium.
well , i supose it's asynchronous request, so the folowing may not work
Ti.API.info("Result for registration = " + this.responseText);
coud you try :
onload : function(e) {
Ti.API.info(this.responseText); // maybe Ti.API.info(this.reponsedata) according to your php.
},
onerror : function(e) {...
in my mind, if you receive JSON information (it trully look's like), you need
this.responseData //instead of this.responseText

How to convert Box's "code" to "token" after user allows access

I'm new at this, trying to hook up Box's API v2. I successfully set up a PHP client library, which I found thanks to the link in the first paragraph on developers.box.com/auth. I've read Box's walkthrough in full more than twice along with roughly 100,000 questions and replies here in regard to the matter. My problem occurs after the user redirects to Box's authorization page, enters his credentials and clicks on "Allow." The results vary according to my redirect_uri and the url of my login page where I've put my client_id and client_secret: 1) If my redirect_uri matches my https://mysite.com/login_with_box, the user redirects to that same url, obviously, which in turn sends the user back to Box's authorization page; and 2) if my redirect_uri differs from https://mysite.com/login_with_box page, then the user successfully returns to my redirect_uri, the url of which includes the 30-second code. I know that I'm close to figuring this out but don't know how to turn the code into a token in 30 seconds or less and use it to show the user's folders, files, info or whatever else. Many thanks for your consideration. Here's where I stand:
// mysite.com/client.php:
// ...
case 'Box':
$this->oauth_version = '2.0';
$this->request_token_url = '';
$this->dialog_url = 'https://api.box.com/oauth2/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&state={STATE}';
$this->append_state_to_redirect_uri = '';
$this->access_token_url = 'https://api.box.com/oauth2/token';
$this->authorization_header = true;
$this->url_parameters = false;
break;
// ...
// mysite.com/login_with_box.php:
// ...
$client->client_id = '[my_client_id]';
$client->client_secret = '[my_client_secret]';
if(($success = $client->Initialize())) {
if(($success = $client->Process())) {
if(strlen($client->access_token)) {
$success = $client->CallAPI(
'https://api.box.com/2.0/users/me',
'GET', array(), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
// ...
It looks like you need your redirect URL to be something different from the URL that initially sends the user through the OAuth process.
For example, you could have https://mysite.com/login_with_box send the user through the OAuth process, and https://mysite.com/receive_box_oauth_response be the URL that is redirected to after the auth process and handles the OAuth response from box.
I figured it out. The problem of course was entirely my fault. Here's how I hooked up the Box API v2 with the PHP OAuth library reccommended by Box:
Create an app on developers.box.com and set the required redirect_uri to something like https://mysite.com/oauth/login_with_box.php.
Download the PHP OAuth library at www.phpclasses.org/package/7700-PHP-Authorize-and-access-APIs-using-OAuth.html
Add something like the following case to PHP OAuth library's oauth_client.php.
case 'Box':
$this->oauth_version = '2.0';
$this->request_token_url = '';
$this->dialog_url = 'https://api.box.com/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&state={STATE}';
$this->append_state_to_redirect_uri = '';
$this->access_token_url = 'https://api.box.com/oauth2/token';
$this->authorization_header = true;
$this->url_parameters = false;
break;
Create something like login_with_box.php and add it to PHP OAuth library. My login_with_box.php reads as follows.
<?php
require('http.php');
require('oauth_client.php');
$client = new oauth_client_class;
$client->server = 'Box';
$client->redirect_uri = 'https://mysite.com/oauth/login_with_box.php';
$client->client_id = 'xxxxxx_BOX_API_CLIENT_ID_xxxxxx';
$client->client_secret = 'xxxxxx_BOX_API_CLIENT_SECRET_xxxxxx';
if(strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('You need an app to do that.');
if(($success = $client->Initialize())) {
if(($success = $client->Process())) {
if(strlen($client->access_token)) {
$success = $client->CallAPI(
'https://api.box.com/2.0/folders/0',
'GET', array('format'=>'json'), array('FailOnAccessError'=>true), $folder);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success) {
?>
<!doctype html>
<html>
<head>
<title>Box OAuth client results</title>
</head>
<body>
<?php echo '<h1>You successfully logged in with Box</h1>'; echo '<pre>', HtmlSpecialChars(print_r($folder, 1)), '</pre>'; ?>
</body>
</html>
<?php } else { ?>
<!doctype html>
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php } ?>
I hope this helps somebody.

Categories