I have tried google captcha using PHP as following way
HTML
<div class="col-md-12">
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6Lf2yUUUAAksikja1XQNtIOqIDmtzb46uHGY-Wq_sl">
</div>
</div>
</div>
PHP
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$secret = '6Lf2yUAAHvAr2QoaNHYFDG945Z6Ai7EqTg6Y71';
//get verify response data
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret=&response=" . rawurlencode($_POST['g-recaptcha-response']) . "&remoteip=" . rawurlencode($_SERVER['REMOTE_ADDR']));
$responseData = json_decode($verifyResponse);
if($responseData->success){
} else {
echo 'Robot verification failed, please try again.';
}
}
This same code has worked in PHP 5.4 But Is not working on PHP 7.0 , i don't know how to fix it, any suggestion or solution please post
You can try in this way.
Hope it will help you.
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$privatekey = "XXXXXXXXXXXXXXXXXXXXXX";
$captcha = $_POST['g-recaptcha-response'];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $privatekey,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data
);
$ch = curl_init();
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
curl_close($ch);
$jsonResponse = json_decode($response);
if ($jsonResponse->success === true) {
}
else {
$errMsg = 'Robot verification failed, please try again.';
}
} else{
$errMsg = 'Please click on the reCAPTCHA box.';
}
You will probably get timeout-or-duplicate issue if your captcha is validated twice. Save logs in a file in append mode and check if you are validating a Captcha twice.
For instance, check below:
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'])
file_put_contents( "logfile", $verifyResponse, FILE_APPEND );
Now, check the logfile created above and try to check if captcha is verified twice.
Related
When implementing recaptcha v2, I am given the error code 'connection-failed' when trying to verify the recaptcha input.
I have followed this (https://www.freakyjolly.com/how-to-add-google-recaptcha-in-php-form/) tutorial as I had no luck with others that I found
require('src/autoload.php');
$siteKey = 'my key';
$secret = 'my key';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$gRecaptchaResponse = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$recaptchaErrors = '';
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
$error[] = "worked";
} else {
$recaptchaErrors = $resp->getErrorCodes();
foreach($recaptchaErrors as $err)
{
$error[] = $err;
}
}
I have not had much luck finding any details on this error anywhere, and it is not documented on the official recaptcha page. I have edited the snippet above for testing purposes, but it would be sending an email.
If allow_url_fopen is off in your php.ini, the connection will fail because Recaptcha uses file_get_contents to access the API by default. I would not enable this flag as it can pose a security risk.
My suggestion, if you have the php curl module installed, is to use Recaptcha with a curl connection:
$recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\CurlPost());
I have had the same problem while working locally in a node environment running node-php-awesome-server.
If you are trying to verify the reCaptcha response from localhost, with a localhost reCaptcha key pair, try from a live webserver (with relative key pair) instead.
For some reason sending the request from localhost returned me that error.
I suppose it has something to do with the development environment but did not investigate further.
I've had the same problem when i tried to include recaptcha in my website on localhost, i then tried this code on my live website(on the server) and it worked, hope this helps.
$secret = 'your server side key from google';
$post_data = http_build_query(
array(
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']));
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data));
$context = stream_context_create($opts);
$response =file_get_contents('https://www.google.com/recaptcha/api/siteverify',false, $context);
$result = json_decode($response);
if($result->success){
echo "Success";
}
if (!$result->success) {
echo "CAPTCHA verification failed.");
}
I'm trying to implement Google ReCaptcha V2 in a PHP form.
Here is my code :
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'], false, stream_context_create($arrContextOptions));
$response = json_decode($response, true);
if($response["success"] === true)
{
echo "Logged In Successfully";
}
else
{
echo "You are a robot";
}
}
?>
When i submit my form, it always return
You are a robot
.
My public key is correct, and my private key too.
I don't know what i'm doing wrong ?
I'm working as localhost.
Thanks.
Just integrated 2 days ago the V2 recaptcha from Google
Try my code below, explicitly to see if is solving your problem:
I can see u do file_get_contents, and i think here is your issues, u have to make POST, please use my code below
if($_SERVER["REQUEST_METHOD"] === "POST"){
// prepare post variables
$post = [
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => 'is optional, but i pass it',
];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$response = json_decode($response, true);
// check result
if(isset($response['success']) && $response['success'] == true){
echo "Logged In Successfully";
}else{
echo "You are a robot";
}
}
I use re-CAPTCHA on my website but it doesn't work when I click LOGIN it says Robot verification failed, please try again I don´t know how to fix it... every time :/
Thanks for help.
If you have better script send me please.
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$secret = '**************';
$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)
{
}else{
echo "<div class='container'><div class='alert alert-danger'><p>Robot verification failed, please try again.</p></div>";
}
}else{
echo "<div class='container'><div class='alert alert-danger'><p>Please click on the reCAPTCHA box.</p></div>";
}
I use ReCaptcha package for Composer when handling captchas.
If you don't know what Composer is, I suggest you head to http://composer.org/
Composer is a PHP dependency manager and it can be really useful when building modern PHP apps.
ReCaptcha Package: https://packagist.org/packages/google/recaptcha
Code samples are also included in the link.
Here is how I handle Google Re-Captcha on the Server:
//process captia response with a custom method.
$captcha = checkCaptia($_POST['g-recaptcha-response']);
if ($captcha){
mailLead();
}
else{
header('location: https://...');
die();
}
Method to handle captcha check...
function checkCaptia($captcha){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret'=>';jaskdf;asdkjf',
'response'=>$captcha,
'remoteip'=>$_SERVER['REMOTE_ADDR']
);
$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 = json_decode(file_get_contents($url, false, $context),TRUE);
return $result;
}
I have a PHP code for sending OTP, When i execute it in my local server its works well. But when i run this code after changing it from my local to server by changing host name etc, i am getting 500 internal server error. I don't know where i am going wrong. Any solution will be apreciated. Thank you
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// echo $_POST['mobile'];
if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$otp = rand(100000, 999999);
$res = $db->createUser($name, $email, $mobile, $otp);
if ($res == USER_CREATED_SUCCESSFULLY) {
// send sms
sendSms($mobile, $otp);
$response["error"] = false;
$response["message"] = "SMS request is initiated! You will be receiving it shortly.";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Sorry! Error occurred in registration.";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Mobile number already existed!";
}
} else {
$response["error"] = true;
$response["message"] = "Sorry! mobile number is not valid or missing.";
}
echo json_encode($response);
function sendSms($mobile, $otp) {
$otp_prefix = ':';
//Your message to send, Add URL encoding here.
$message = urlencode("Hello Your OPT is '$otp_prefix $otp'");
$response_type = 'json';
//Define route
$route = "4";
//Prepare you post parameters
$postData = array(
'authkey' => AUTH_KEY,
'mobiles' => $mobile,
'message' => $message,
'sender' => SENDER_ID,
'route' => $route,
'response' => $response_type
);
//API URL
$url = "https://control.otp.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
?>
I dont think the 500 error comes from your code. That's likely an Apache config related problem. Possibly a stray .htaccess or php.ini got uploaded, or is syntactically wrong for the version of Apache you have on the server.
I'm trying to revoke the access from a web app. This is my code:
When the user do login:
$scriptUri = "http:...";
$client = new Google_Client();
$client->setAccessType('online');
$client->setApplicationName('xxx');
$client->setClientId('xxx');
$client->setClientSecret('xxx');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('xxx'); // API key
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));
$oauth2 = new Google_Service_Oauth2($client);
if (isset($_GET['code']) && isset($_GET["google"])){
$client->authenticate($_GET['code']);
$token = $client->getAccessToken();
$client->setAccessToken($token);
$_SESSION['google_token'] = $token;
}
And here is the code when I want to revoke the app:
$ch = curl_init("https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'].";");
curl_exec($ch);
curl_close($ch)
The result is a NOT FOUND page saying The requested URL /v2/{ "error" : "invalid_token"} was not found on this server.
I'm not sure if this is the correct way to revoke the access.
Thanks.
I tried your code and had the same error.
Take a look at how you have concatenated the strings at:
$ch = curl_init("https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'].";");
PHP easily lets committing syntax errors over concatenated strings. The fixed that worked for me was:
$RevokeTokenURL="https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'];
$ch = curl_init($RevokeTokenURL);
And in case you need it, my complete code is:
if(isset($_GET['action']) && $_GET['action'] == 'logout') {
session_destroy();
header('Location:'.$RedirectURL);
$RevokeTokenURL="https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'];
$ch = curl_init($RevokeTokenURL);
curl_exec($ch);
curl_close($ch);
}
I think this should work..
$revokeURL = "https://accounts.google.com/o/oauth2/revoke?token=".$access_token;
$ch = curl_init();
$options = array(
CURLOPT_URL => $revokeURL,
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true, //verify HTTPS
CURLOPT_SSL_CIPHER_LIST => 'TLSv1'); //remove this line if curl SSL error
curl_setopt_array($ch, $options); //setup
$response = curl_exec($ch); //run
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get HTTP code
if ($httpCode == 200)
{
echo "Success"; // .$response;
}
else
{
echo "Error : ".$httpCode."__".curl_error($ch);
}
curl_close($ch);```
Based on https://developers.google.com/accounts/docs/OAuth2WebServer#tokenrevoke