google recaptcha error in codeigniter php while submiting form - php

i have created a form in codeigniter and given a google captcha v2, i have created the site key and secret key added it to config files, and also added the js and the recaptcha div including my site key. the following is my captcha function in controller:
public function validate_captcha() {
$recaptcha = trim($this->input->post('g-recaptcha-response'));
$userIp= $this->input->ip_address();
$secret='xxxxxxxxxxxx'; (i have given my scret key here)
$secretdata = array(
'secret' => "$secret",
'response' => "$recaptcha",
'remoteip' =>"$userIp"
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($verify);
$status= json_decode($response, true);
if(empty($status['success'])){
return FALSE;
}else{
return TRUE;
}
}
the following is my register form function in same controller:
public function ajaxRegAction() {
$this->load->library('session');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$this->load->library('form_validation');
$utype='W';
$dhamu = $this->validate_captcha();
$createddate = date('Y-m-d h:i:s');
$createdby = '0';
$mobile = $this->input->post('phone');
$form_data = array(
'type' => $utype,
'unique_id' => $this->mainModel->generateIndividualID(),
'phone_num' => $mobile,
'email' => $this->input->post('email'),
'first_name' => $this->input->post('firstname'),
'last_name' => $this->input->post('lastname'),
'created_by' => $createdby,
'created_date' => $createddate,
);
$name = $this->input->post('firstname')." ".$this->input->post('lastname');
$access_info = array('user_type'=>$utype);
$check = $this->mainModel->checkUserAvail($this->input->post('phone'),$this->input->post('email'));
$checkauser = $this->mainModel->checkAjaxUser($this->input->post('phone'),$this->input->post('email'));
if($check==0) {
if($dhamu==1){
$insert = $this->mainModel->ajaxRegInsertUser($form_data, $access_info,$this->input->post('password'));
$message="Dear ".$this->input->post('firstname').", You have successfully registered with Book The Party. Thank You for coming On-Board. Contact us at 9666888000 for any queries - Team BTP";
$email_message=$message;
$message=rawurlencode($message);
$this->mainModel->sendOtptoCustomer($mobile,$message);
$this->mainModel->sendmailtoCustomer($this->input->post('email'),$email_message);
echo "success";
}
else{ echo "Captcha Error";}
}
else{
echo "Registration Failed !";
}
even if i check the google recaptcha box and press register, the form is showing "Captcha Error", values are not being added to the database also. can anyone please tell me what could be wrong here, thanks in advance

Step 1:
Make sure you have added localhost in your domain in Google Captcha V2 dashboard.
Step 2:
I am modifying your function you can use it like this:
public function validate_captcha()
{
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
return TRUE;
} else {
return FALSE;
}
}
instead of CURL
Do let me know if this works

Related

Recaptcha V2 return false PHP

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";
}
}

How do i fix my JSON format by using php

I try to send json format to my android app , but i find that my json format is uncorrect.
{data={"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, flag=0, title=Google Cloud Messaging, is_background=false}
I set the data like this:
$app->post('/users/send_to_all',
function() use ($app) {
$response = array();
verifyRequiredParams(array('user_id', 'message'));
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$db = new DbHandler();
$user_id = $app->request->post('user_id');
$message = $app->request->post('message');
require_once __DIR__ . '/../libs/gcm/gcm.php';
require_once __DIR__ . '/../libs/gcm/push.php';
$gcm = new GCM();
$push = new Push();
//get the user using userid
$user = $db->getUser($user_id);
//creating tmp message , skipping database insertion
$msg = array();
$msg['message'] = $message;
$msg['message_id'] = '';
$msg['chat_room_id'] = '';
$msg['created_at'] = date('Y-m-d G:i:s');
$data = array();
$data['user'] = $user;
$data['message'] = $msg;
$data['image'] = 'http://www.androidhive.info/wp-content/uploads/2016/01/Air-1.png';
$push->setTitle("Google Cloud Messaging");
$push->setIsBackground(FALSE);
$push->setFlag(PUSH_FLAG_USER);
$push->setData($data);
//sending message to topic `global`
//on the device every user should subscribe to `global` topic
$gcm->sendToTopic('global', $push->getPush());
$response['user'] = $user;
$response['error'] = false;
echoRespnse(200, $response);
});
Here is my Push.php about getPush():
public function getPush() {
$res = array();
$res['title'] = $this->title;
$res['is_background'] = $this->is_background;
$res['flag'] = $this->flag;
$res['data'] = $this->data;
return $res;
}
Here is my Gcm.php about sendToTopic:
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
I'm really not familiar with php , how do i fix the JSON format ?
Any help would be appreciated , thanks in advance !
I update my question , i find json_encode in my Gcm.php:
It's on curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
class GCM {
//constructor
function __construct() {
}
//sending push message to single user by gcm registration id (array 最後面有, 待看)
public function send($to, $message) {
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending message to a topic by topic id
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//sending push message to multiple users by gcm registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
//function makes curl request to gcm servers (__DIR__ 待看)
private function sendPushNotification($fields) {
//include config
include_once __DIR__ . '/../../include/config.php';
//Set POST variable
//$url = 'https://gcm-http.googleapis.com/gcm/send';
$url='https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//open connection
$ch = curl_init();
//set the url , number of POST vars , POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//Execute post (=有三個?)
$result = curl_exec($ch);
if ($result === FALSE){
die('Curl failed: '. curl_error($ch));
}
//close connection
curl_close($ch);
return $result;
}
}
?>
It's still let my json format incorrect , how do i fix ?
PHP has some built-in json functions, you need json_encode() and json_decode().
For example this code:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Will print:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Here's the link to documentation for json_encode() and for the entire json in php documentation.
Hope this helps.
Your JSON is invalid. try:
{"data":{"image":"http:\/\/www.androidhive.info\/wp-content\/uploads\/2016\/01\/Air-1.png","message":{"chat_room_id":"","created_at":"2017-03-22 3:34:30","message_id":"","message":"77"},"user":{"user_id":null,"gcm_registration_id":null,"name":null,"created_at":null,"email":null}}, "flag":0, "title":"Google Cloud Messaging", "is_background":false}
Notice ive replaced usage of = with : and wrapped keys and strings in quotes (")
To get it into a nice json string with php you need to build your array correctly first. Possible way is to setup a response array and then you can json_encode() it.
$response =[
'data' => $data,
'flag' => 0,
'title' => 'Google Cloud Messaging',
'is_background' => false.
];
now you can
json_encode($response);

Quickblox error "incorrect event" sending a push notification with AP

I'm using Quickblox to send push notifications to iPhone users. I created PHP functions for session and creating a user and API is working fine, but testing sending a push notification, I got an error on Dashboard/Queue: "incorrect event" on the message column. The event is created but never arrived.
The response of the API is OK, like the documentation.
I don't know why I got that error.
This is my code:
if (isset($_POST['mensaje'])) {
// Quickblox user Sign Up
$session = createSession( . . . , '...', '...', '...', '...');
$token = $session->token;
$group = '...'; // Hardcoded only for testing
$resp = sendQBPush($_POST['mensaje'], $group, $token);
}
and the function:
function sendQBPush($msg, $group, $token)
{
if (!$msg) {
return false;
}
$message = base64_encode($msg);
// Build post body
$post_body = array(
'event' => array(
'notification_type' => 'push',
'environment' => 'production',
'user' => array(
'tags' => array(
'any' => $group
)
) ,
'push_type' => 'apns',
'message' => 'payload=' . $message
)
);
$request = json_encode($post_body);
$ch = curl_init('http://api.quickblox.com/events.json');
curl_setopt($ch, CURLOPT_POST, true); // Use POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $request); // Setup post body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.0',
'QB-Token: ' . $token
));
$resultJSON = curl_exec($ch);
$responseJSON = json_decode($resultJSON);
echo $resultJSON;
// Check errors
if ($responseJSON) {
return $responseJSON;
}
else {
$error = curl_error($curl) . '(' . curl_errno($curl) . ')';
return $error;
}
// Close connection
curl_close($curl);
}
Thanks for your help

Posting content to Tumblr

I have already tried below code,
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
You need to use the proper Tumblr endpoint:
http://www.tumblr.com/api/write
I'm pretty sure the others won't work.
Obviously make sure that your user and pass are correct, other than that, this looks fine - it's pretty much exactly what I'd write.

post to tumblr using php

Could anyone help me figure out how to post to tumblr using php.
I tried googling for a library or a sample code but couldn't find one. all I can find is this here https://github.com/alexdunae/tumblr-php/blob/master/Tumblr.php and it doesnt seem to work also I looked and tried the code on v1 api at tumblr website that doesnt work either ....
function post($data){
if(function_exists("curl_version")){
$data["email"] = $this->email;
$data["password"] = $this->password;
$data["generator"] = $this->generator;
$request = http_build_query($data);
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c,CURLOPT_POST,true);
curl_setopt($c,CURLOPT_POSTFIELDS,$request);
curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
$return = curl_exec($c);
$status = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if($status == "201"){
return true;
}
elseif($status == "403"){
return false;
}
else{
return "error: $return";
}
}
else{
return "error: cURL not installed";
}
}
Thanks for the help
I just noticed that this is showing up as Featured for Tumblr and I want to say this: As of 2012, you should IGNORE the above answer by Tuga because it DOES NOT work with the newest Tumblr API.
What you need is TumblrOAuth which is built from OAuth Sandbox.
It is only setup to read and write Tumblr posts, so if you want to do more than that, you'll need to alter the code. I used it as my code base for Followr.
Stolen from http://www.tumblr.com/docs/en/api
// Authorization info
$tumblr_email = 'info#davidville.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'regular';
$post_title = 'The post title';
$post_body = 'This is the body of the post.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
?>
$conskey = "CONSUMER KEY";
$conssec = "CONSUMER SECRET";
$tumblr_blog = "myblog.tumblr.com";
$to_be_posted = "This is the text to be posted";
$oauth = new OAuth($conskey,$conssec);
$oauth->fetch("http://api.tumblr.com/v2/blog/".$tumblr_blog."/post", array('type'=>'text', 'body'=>$to_be_posted), OAUTH_HTTP_METHOD_POST);
$result = json_decode($oauth->getLastResponse());
if($result->meta->status == 200){
echo 'Success!';
}
This code will let you post to your tumblr blog using tumblr API.
I hope this code helps.
The api example provided by Tuga is working for me (on Wordpress)...so I think your problem lies elsewhere, and not with the example provided. I would also be very appreciative if you guys got a version 2 api working if you could post it.

Categories