Why No response from Google Invisible recaptcha? - php

Trying to achieve Google invisible recaptcha, but I am not getting any response after verification.
Here is my code:
invisible_recaptcha.php (form)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recaptcha Demo</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("i-recaptcha").submit();
}
</script>
</head>
<body>
<!-- FORM GOES HERE -->
<form id='i-recaptcha' action="process_recaptcha.php" method="post">
<label for="fname">First Name*</label><br>
<input type="text" name="fname" id="fname" required autofocus><br><br>
<label for="lname">Last Name*</label><br>
<input type="text" name="lname" id="lname" required><br><br>
<label for="email">Email Address*</label><br>
<input type="email" name="email" id="email" required><br><br>
<button class="g-recaptcha" data-sitekey="XXXXXXmy_site_keyXXXXXXXXX" data-size="invisible" data-callback="onSubmit">
Submit
</button>
</form>
</body>
</html>
process_recaptcha.php (verify the recaptcha)
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'XXXXXX_my_secret_key_XXXXXXXXX',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
//echo $user_response."<br><br><br><br>". $fields_string;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the reCAPTCHA is not properly set up
echo 'reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.';
} else {
// If CAPTCHA is successful...
// Paste mail function or whatever else you want to happen here!
echo '<br><p>CAPTCHA was completed successfully!</p><br>';
}
} ?>
It always gives me this message:
reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.

Please try this One
try {
//Get google capcha details
if ($site_details['google_captcha_secret_key'] != '') {
$site_key = $site_details['google_captcha_secret_key'];
} else {
$site_key = GOOGLE_CAPTCHA_SECRET_KEY;
}
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => $site_key,
'response' => $captcha,
'remoteip' => $this->userIpAddress];
$options = [
'http' => [
'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);
return json_decode($result)->success;
} catch (Exception $e) {
return null;
}

Make sure you double-check your code over for syntax errors. You are missing the left quote around your site key. You also have an extra parenthesis where it says json_decode.
Finally, you don't need to separate it into two PHP files if you are going to use this condition:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
So the php code in process_recaptcha.php can be embedded in invisible_recaptcha.php. You would then have to change the form's action attribute to itself (invisible_recaptcha.php). The condition will check if the form has been submitted yet. If is has, it will process your recaptcha code, if not, it will skip it.

Related

Fix request failed using php

I make an api using Linkedin for website. After created all files, my application run fine but the only that has problem is when I try to allow the website, gives me this errors:
my purpose is to access in this page:
My code has error in this line:
init.php
<?php
SESSION_start();
$client_id="xxxxxxxxxxxxxx";
$client_secret="xxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token = "random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
function curl($url, $parameters)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_POST, 1);
$header =[];
$header[] = "Content-type:applicationx-www-form-urlencoded";
$result = curl_exec($ch);
return $result;
}
function getCallback()
{
$client_id="xxxxxxxxxxxxxx";
$client_secret="jxxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token ="random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
}
if(isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$url = "https://www.linkedin.com/oauth/v2/accessToken";
$params = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
'grant_type' => 'authorization_code',
];
$accessToken = curl($url, http_build_query($params));
$accessToken = json_decode($accessToken)->access_Token;
$URL="https://api.linkedin.com/v1/people/~:(id,firstName,lastName,pictureUrls::(original),headline,publicProfileUrl,location,industry,positions,email-address)?format=json&oauth2_access_token=" .$accessToken;
$user = file_get_contents($url, false);
return(json_decode($user));
}
?>
Callback.php:
<?php
require_once "init.php";
$user = getCallback();
$_SESSION['user'] = $user;
header("location: landing.php");
?>
And this is the landing page:
<?php
require "init.php";
if(!isset($_SESSION['user'])) {
$user = 0;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
<body style="margin-top:200px; text-align:center;">
<div>
<h1>successful</h1>
<h1>here is describing your details info</h1>
<label style="font-weight:600">First Name</label><br>
<label><?php echo $user['firstName'] ?></label><br><br>
<label style="font-weight:600">Last Name</label><br>
<label><?php echo $user['lastName'] ?></label><br><br>
<label style="font-weight:600">Email address</label><br>
<label><?php echo $user['emailaddress'] ?></label><br><br>
<label style="font-weight:600">Headline</label><br>
<label><?php echo $user['headline'] ?></label><br><br>
<label style="font-weight:600">Industry</label><br>
<label><?php echo $user['industry'] ?></label><br><br>
<button>Log out</button>
</div>
</body>
</html>
the x it is for secure reason, I have put $client_secret="", $client_id="".
In this project I want to see my profile completed with details on landing page and not empty as it's show here for example in first name to be writen a name and ect.
how to fix those errors,thanks
The first error (Undefined property) is because the HTTP request didn't get a valid response ($accessToken) in:
$accessToken = curl();
This could be because the URL requested is invalid. You can:
Check if $params array is correctly set. Call print_r($params) or print_r(http_build_query($params)) before calling curl to check it.
Check if the curl() call has the right parameters (url and parameters) it could be better to use only a full url ($url . "?" . http_build_query($params)) if the request is using GET, but
The accessToken API must be requested as POST request (not GET), so make sure your cUrl call sends a POST request (See: https://developer.linkedin.com/docs/oauth2#)
The second error is related to the first one, because the access token is empty, you get a HTTP 400 error (bad request). So if you fix the first step the second could be fine.
try this code before $accessToken :
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
return true;
this make solute the error message

php forms return data back to .html page

This should be a pretty simple questions but I can't seam to find a simple answer. All of the questions I find deal with same jquery.
I have a php page that accepts for post data, places it in an array, passes the array to an api, and receives success/error from api.
I have an html page with a form. When I submit the form it passes the form data to the php file.
All I would like to do is return the success/error message's variable back to the html file. I don't care if the page reloads, I don't want any fancy features I'm just trying to do a simple test but have forgotten my php 101. any help or direction to references would be appreciated.
Html:
<div style="width: 400px; margin: 150px auto;">
<form action="api3.php" method="post">
<input type="text" placeholder="First Name" name="fname"><br><br>
<input type="text" placeholder="Last Name" name="lname"><br><br>
<input type="email" placeholder="Email" name="email"><br><br>
<input type="text" placeholder="Phone" name="phone"><br><br>
<select name="life"><br><br>
<option value="customer">Customer</option>
<option value="lead">Lead</option>
<option value="subscriber">Subsciber</option>
<option value="opportunity">Opportunity</option>
</select><br><br>
<input type="text" placeholder="Pizza" name="pizza"><br><br>
<input type="submit" value="Submit">
</form>
</div>
PHP:
<?php
$arr = array(
'properties' => array (
array(
'property' => 'email',
'value' => $_POST["email"]
),
array(
'property' => 'firstname',
'value' => $_POST["fname"]
),
array(
'property' => 'lastname',
'value' => $_POST["lname"]
),
array(
'property' => 'phone',
'value' => $_POST["phone"]
),
array(
"property" => "lifecyclestage",
"value" => $_POST["life"]
),
array(
"property" => "pizza",
"value" => $_POST["pizza"]
)
)
);
$post_json = json_encode($arr);
$hapikey = "/";
$endpoint1 = 'http://api.hubapi.com/contacts/v1/contact/createOrUpdate/email/' . $arr['properties'][0]['value'] . '/?hapikey=' . $hapikey;
$endpoint2 = 'http://api.hubapi.com/contacts/v1/lists/5/add?hapikey=' . $hapikey;
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
#curl_setopt($ch, CURLOPT_URL, $endpoint1);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response1 = #curl_exec($ch);
$status_code1 = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors1 = curl_error($ch);
if ($status_code1 == 200) {
$vid = json_decode($response1, true);
echo $vid['vid'] . '<br><br><br>';
$arr2 = array(
'vids' => array (
$vid['vid']
)
);
$vids_push = json_encode($arr2);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $vids_push);
#curl_setopt($ch, CURLOPT_URL, $endpoint2);
$response2 = #curl_exec($ch);
$status_code2 = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors2 = curl_error($ch);
#curl_close($ch);
return $response2;
}
?>
EDIT: I changed my form.html page to .php. I didn't want to share my code because it always seams to complicate things but all I want is to return $response2 back to my form.php page.
First of all the page you have form and want to get response should be with .php
Now for example, I have a page with form at www.example.com/work.php
//Your form here
<form> </form>
submit the form on other .php page that process input and get response from API.
at the end of page you have two methods to return data.
using GET
encode your variables in url and redirect page to work.php
$url = "www.example.com/work.php" + "?status=error&message=This is message";
header('Location: '.$url);
Now on work.php file you need to utilize these parameters we encoded with url using
echo $_GET['status'];
echo $_GET['message'];
// rest of the page will be same.
using SESSION
store variables in session and redirect to work.php without parameters
$_SESSION['status'] = "error";
$_SESSION['message'] = "This is message";
$url = "www.example.com/work.php";
header('Location: '.$url);
Again in work.php file display data from session and rest of code will be same.

How to get cURL response from absolute URL by posting POST parameters to different website in PHP?

I want to get response from the URL http://webcache.gmc-uk.org/gmclrmp_enu/start.swe by sending some POST parameters into it.
I have written a function as follows:
public function getResponse($params, $url)
{
$post_data = '';
foreach ($params as $key => $value) {
$post_data .= $key . '=' . $value . '&';
}
//create the final string to be posted using implode()
$post_data = rtrim($post_data, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($post_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
But, when I call this function as:
public function getIndex()
{
$params = array(
"s_3_1_5_0" => "5205500"
);
$url = 'http://webcache.gmc-uk.org/gmclrmp_enu/start.swe';
echo $this->getResponse($params, $url);
}
I am always redirected to the page: http://localhost:8000/gmclrmp_enu/start.swe
instead of getting response from the specified URL.
where, http:// localhost:8000/ is root URL of my local project.
How could I get the response from that URL and dump it?
I tried your code and got this response.
<html>
<body>
<form action="/gmclrmp_enu/start.swe" method="POST" name="RedirectForHost">
<input type = "hidden" name="s_3_1_5_0" value="5205500">
<input type = "hidden" name="SWEBHWND" value="">
<input type = "hidden" name="_sn" value="QG3N3byeQ-lw2X0470Taoo2Mr1xU6fklSaK4bX.yXOH1DqcEpmRHVzctRxa1UYflcu-svwV7M0VFB6KvWmUEh4mUDGbJtaXeil1PnikFKVpr6fRP.i-GMhMRm41kZVFHaZA1QBjteOlfTXcwF0CLSh.MzwHUhdPVvYK9Ulfe.zCJQiSkU2XOt68YjT1lD-4jrTrIBzxJLUY_">
<input type = "hidden" name="SRN" value="">
<input type = "hidden" name="SWEHo" value="">
<input type = "hidden" name="SWETS" value="1481276787">
</form>
<script language="javascript">
var formObj = document.forms["RedirectForHost"];
formObj.SWEHo.value=top.location.hostname;
formObj.submit();
</script>
</body>
</html>
I think you got response like this, and then javascript submitted the form to localhost:8000.

Use input value as an array variable

I'm totally new to php. I'm trying to echo the value of an input field into a an array but it doesn't seem to work.e.g echo the value of hidden-input as the value for origin in the array. How can I achieve this?
<form method="post">
<!-- Set type -> Hidden, if you want to make that input field hidden.
You really should use better "names" for the input fields -->
// I populate the value with jQuery //
<input id="hidden-input" type="hidden" name="from" value="">
</form>
<?php
$params = array(
'origin' => $_post['from'],
'destination' => um_user('postal_zip_code'),
'sensor' => 'true',
'units' => 'imperial'
);
$params_string='';
// Join parameters into URL string
foreach($params as $var => $val){
$params_string .= '&' . $var . '=' . urlencode($val);
}
// Request URL
$url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');
// Make our API request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
// Parse the JSON response
$directions = json_decode($return);
//echo"<pre>";
//print_r($directions);
// Show the total distance
echo '<p><strong>Total distance:</strong> ' . $directions->routes[0]->legs[0]->distance->text . '</p>';
?>
<div id class="distance"></div>
The jQuery that inserts the value looks like below and it works perfectly. It inserts it as supposed but the php doesn't pass it to the array
$(document).ready(function() {
var someName = $('.um-field-postal_zip_code .um-field-value').text();
$("input#hidden-input").attr("value", someName);
});
<form method="post">
<!-- Set type -> Hidden, if you want to make that input field hidden.
You really should use better "names" for the input fields -->
<input id="hidden-input" type="hidden" name="from" value="">
</form>
<?php
$params = array(
'origin' => $_POST['from'], // <- Now it should be empty, because nothing is inside
'destination' => um_user('postal_zip_code'),
'sensor' => 'true', // If you write 'false' it's still true, because the string is filled. Please use correct bools like true / false without the quotes // 'sensor' => true
'units' => 'imperial'
);
?>
You also need something to "send" or "activate" the form.
<input type="submit" name="sendForm" value="Send Form"/>
So the input form looks like:
<form method="post">
<!-- Set type -> Hidden, if you want to make that input field hidden.
You really should use better "names" for the input fields -->
<input id="hidden-input" type="hidden" name="from" value="">
<input type="submit" name="sendForm" value="Send Form"/>
</form>
Let me know, if you need more help!
html
<form method="post" action="yourpage.php">
<input id="hidden-input" name="from" value="">
<input type="submit" value="Submit" name="submit_button">
</form>
php
<?php
//if your form is submitted fill the array
if(isset($_POST['submit_button'])){
$params = array(
'origin' => $_POST['from'],
'destination' => 'postal_zip_code',
'sensor' => 'true',
'units' => 'imperial'
);
//print array
foreach($params as $index=>$value){
print $index." :".$value;
}
}
?>
You can not fetch data from form without refresh of page. Actually you are trying to fetch data from hidden input which is coming from jquery.
First remove form html and make ajax call
You need to set ajax
$(document).ready(function() {
var someName = $('.um-field-postal_zip_code .um-field-value').text();
if(!someName==''){//check somename is blank or not
//make ajax call
$.ajax({url: "url of your php code",
data : 'someName',
type : 'post',
success: function(result){
}});
}
});
In php file fetch data using $_post
echo $data = $_post['data'];//this is your origin
Now continue with your code
$params = array(
'origin' => $data,
'destination' => um_user('postal_zip_code'),
'sensor' => 'true',
'units' => 'imperial'
);
$params_string='';
// Join parameters into URL string
foreach($params as $var => $val){
$params_string .= '&' . $var . '=' . urlencode($val);
}
// Request URL
$url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');
// Make our API request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
// Parse the JSON response
$directions = json_decode($return);
//echo"<pre>";
//print_r($directions);
// Show the total distance
echo '<p><strong>Total distance:</strong> ' . $directions->routes[0]->legs[0]->distance->text . '</p>';

Cakephp : Validate recaptcha

I have downloaded a recaptchalib and successfully implemented the recaptcha and its displaying the recaptcha on my page but i am not able to validate it ... how can i validate the recaptcha
In View File
<div id="recaptcha_div"></div>
<script type="text/javascript">
$(function(){
Recaptcha.create("<?php echo Configure::read("recatpch_settings.public_key")?>", 'recaptcha_div', {
theme: "red",
callback: Recaptcha.focus_response_field});
});
</script>
Controller's Login action
public function login() {
App::import('Vendor', 'recaptchalib', array('file' => 'recaptchalib/recaptchalib.php'));
$resp = recaptcha_check_answer (Configure::read("recatpch_settings.private_key"),
$_SERVER["REMOTE_ADDR"],
$this->params['form']["recaptcha_challenge_field"],
$this->params['form']["recaptcha_response_field"]);
pr($resp);
exit();
if (!$resp->is_valid) {
$this->Session->setFlash('The reCAPTCHA wasn\'t entered correctly. Please, try again.');
} else {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
}
}
I am not able to validate the captcha. I want to login the user if i types the correct captcha and obviously username and password.
I know that this is a very old question by now but I'll just go ahead and answer for those who might be looking into implementing this.
Add the Site/Secret key to your app/config/bootstrap.php file.
//Recaptcha Config
Configure::write('Recaptcha.SiteKey','YourSiteKey');
Configure::write('Recaptcha.SecretKey','YourSecretKey');
Adding the reCaptcha widget to your view/form:
<div>
<div class="g-recaptcha"
data-sitekey="<?php echo Configure::read('Recaptcha.SiteKey'); ?>">
</div>
<?php echo $this->Html->script('https://www.google.com/recaptcha/api.js"'); ?>
</div>
Verifying the user's response (reusable function inside your controller):
private function __checkRecaptchaResponse($response){
// verifying the response is done through a request to this URL
$url = 'https://www.google.com/recaptcha/api/siteverify';
// The API request has three parameters (last one is optional)
$data = array('secret' => Configure::read('Recaptcha.SecretKey'),
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
// We could also use curl to send the API request
$context = stream_context_create($options);
$json_result = file_get_contents($url, false, $context);
$result = json_decode($json_result);
return $result->success;
}
You check response by calling the above function after submitting a form containing the widget:
if($this->__checkRecaptchaResponse($this->request->data['g-recaptcha-response'])){
// user solved the captcha
} else {
// user failed to solve the captcha
}
Useful resources:
https://developers.google.com/recaptcha/docs/display
https://developers.google.com/recaptcha/docs/verify
Google has been introduced new reCaptcha API which is Are you a robot? A new design captcha system. This protects your website for robots and spammers, in this post I had implemented new reCaptch API system with HTML login form using CakePHP. Please take a look quick look at the demo.
Get reCaptcha Key
Click here to create a Google reCaptcha application.
Register Your Website
Give your website domain details without http:
Google Site Key
You will use this in HTML code.
Google Secret Key
This will help your website to communication with Google.
HTML code
Contains HTML code with Google reCaptcha snippet. You have to modify the GOOGLE_SITE_KEY value.
<html>
<head>
/* Google reCaptcha JS */
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form action="" method="post">
<label>Username</label>
<?php echo $this->Form->text('User.username', array('maxlength' => 32))?>
<label>Password</label>
<?php echo $this->Form->password('User.password', array('maxlength' => 32))?>
<div class="g-recaptcha" data-sitekey="GOOGLE_SITE_KEY"></div>
<input type="submit" value="Log In" />
</form>
</body>
</html>
Create new Vendor in Vendor file:
curl.php
<?php
function getCurlData($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
$curlData = curl_exec($curl);
curl_close($curl);
return $curlData;
}
?>
Using in controller, You have to modify the GOOGLE_SECRET_KEY value.
$recaptcha = $this->data['g-recaptcha-response'];
$google_url = "https://www.google.com/recaptcha/api/siteverify";
$secret = 'GOOGLE_SECRET_KEY';
$ip = $_SERVER['REMOTE_ADDR'];
$url = $google_url . "?secret=" . $secret . "&response=" . $recaptcha ."&remoteip=" . $ip;
App::import('Vendor', 'curl');
$res = getCurlData($url);
$res = json_decode($res, true);
if(empty($res['success'])){
//if success not empty
//some code here
}
Hope it's useful.

Categories