I'm trying to implement this Recaptcha request into my sign-up form, however it isn't working. The cURL/JSON request returns null when I successfully validate the Recaptcha on my website.
I tried using var_dump on the "error-codes": from the JSON request, and it only returns null; whereas in this document it shows that it is clearly meant to output two items in the JSON request.
Thanks in advance, I haven't done much work with JSON/cURL, so be easy on me.
Here's my code:
PHP
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$recaptcha = $_POST['g-recaptcha-response'];
if(!empty($recaptcha)) {
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;
}
$google_url = "https://www.google.com/recaptcha/api/siteverify";
$secret = 'You will never know >:D';
$ip = $_SERVER['REMOTE_ADDR'];
$url = $google_url . "?secret=" . $secret . "&response=" . $recaptcha . "&remoteip=" . $ip;
$res = getCurlData($url);
$res = json_decode($res, true);
// var_dumping returns null
var_dump($res);
//reCaptcha success check
if($res['success'] == true) {
echo "Recaptcha was successfully validated";
} else {
echo "Recaptcha was not validated, please try again";
}
} else {
echo "You didn't validate the Recaptcha";
}
}
?>
HTML
<form action="home.php" method="post">
<div class="g-recaptcha" data-sitekey="I removed it for this post"></div>
<input class="btn btn-primary" type="submit" name="submit" value="SIGN UP" />
</form>
Here is my code running without problem:
Client Side:
<div class="g-recaptcha" data-sitekey="PUBLIC_KEY"></div>
Server Side:
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
$privatekey = "SECRET_KEY";
$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) {
doSomething();
}
else {
doSomeOtherThing();
}
Working here! :)
Your problem is probably with the SSL certificate.
You can put this line to let curl ignore it:
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)
However, you can put this to test on your localhost but when uploading your website, it is better to have an SSL certificate and this line removed.
Api says: METHOD: POST, you are sending "GET" request.
Check CURLOPT_POST and CURLOPT_POSTFIELDS option on http://php.net/manual/en/function.curl-setopt.php
EDIT:
I just checked the API, it work with GET too. I don't see any error in your code. Could you temporary change your function to:
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);
if (!$curlData) {
throw new \Exception('Curl error: ' . curl_error($curl));
}
curl_close($curl);
return $curlData;
}
Related
I have been working on setting up the frase api. and created the following curl snippet.
<?php
$url = 'http://api.frase.io/api/v1/process_url';
//The data you want to send via POST
$fields = ['url' => 'https://firstsiteguide.com/best-gaming-blogs/', 'token' => "dd528796a9924dae9962bc5bd7ccdb20"];
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($fields));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0');
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo "<br/>CURL ERROR: ". $error_msg ."<br/>";
}else{
print "curl response is:" . $response ;
}
curl_close ($ch);
?>
I am not sure why, But I am receiving the following error for the same
The requested URL returned error: 400 Bad Request
Can help me identify what part of code I am missing or doing wrong. Thank you so much in advance.
You're passing the token as a body parameter instead of a header. The body parameter needs to be sent as a JSON encoded string as mentioned on the API documentation page. Also, you need to remove or at least increase the cURL timeout value as it takes time to fetch, process and return a value from the API end. Note that the API will return the response in JSON format.
So, the complete code should be as:
<?php
$url = 'http://api.frase.io/api/v1/process_url'; //The endpoint url you want to send data via POST
$headers = ['token: dd528796a9924dae9962bc5bd7ccdb20']; // add this line, headers
$fields = ['url' => 'https://firstsiteguide.com/best-gaming-blogs/']; // modify this line, body
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // add this line
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); // modify this
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0');
$response = curl_exec($ch);
if (curl_errno($ch))
{
$error_msg = curl_error($ch);
echo "<br/>CURL ERROR: " . $error_msg . "<br/>";
}
else
{
print($response);
// $values = json_decode($response, true); // this is an array with all the values
}
curl_close($ch);
?>
I have a form which uses curl to submit the apiKey to my server and then the script on my server verify the key and returns true and false. but instead of response. I'm getting Trying to access array offset on value of type null. I want to know How to get response from my server after curl submission.
Curl Submit
$post['apiKey'] = $apiKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$json = curl_exec($ch);
$response = json_decode($json, true);
Server Script
<?php
define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");
require("includes/initialize.php");
if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");
$postParams = allowedPOSTParams($allowed_params=['apiKey']);
if (!isset($postParams['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");
$apiKey = escape($postParams['apiKey']);
if (isInputEmpty($apiKey)) {
header(ERROR_HEADER_URL . "emptyFields");
} elseif (!$apiKey == 25) {
header(ERROR_HEADER_URL . urlencode("invalidKey"));
} else {
$response = [];
if (getApiKeyUserDetails($apiKey, $connection)) {
if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) {
$response['success'] = false;
$response['error'] = 'apiKeyUsed';
} else {
makeApiKeyUsed($apiKey, $connection);
$response['success'] = true;
}
} else {
$response['success'] = false;
$response['error'] = 'invalidApiKey';
}
return json_encode($response);
}
Allowed Post Params Function:
function allowedPOSTParams($allowed_params=[]) {
$allowed_array = [];
foreach ($allowed_params as $param) {
if (isset($_POST[$param])) {
$allowed_array[$param] = $_POST[$param];
} else {
$allowed_array[$param] = NULL;
}
}
return $allowed_array;
}
Replace
curl_setopt($ch, CURLOPT_POSTFIELDS, $apiKey);
with
curl_setopt($ch, CURLOPT_POSTFIELDS, array('apiKey'=>$apiKey));
Then, you will able to find apiKey as POST parameter.
i am new to api so i may be completely wrong.
i was going through some docuementaion in github but could not find some answers so i am here
i want to pass url of these functions to api.php
after validating these key and secret.when i echo these data i get key, secret and url but how to get these details in php as its not a post and i cant use _post function to manipulate data based on url submitted and give the result
public function __construct($key = '', $secret = '', $timeout = 30,
$proxyParams = array()) {
$this->auth = array(
"auth" => array(
"api_key" => $key,
"api_secret" => $secret
)
);
$this->timeout = $timeout;
$this->proxyParams = $proxyParams;
}
public function url($opts = array()) {
$data = json_encode(array_merge($this->auth, $opts));
// echo $data;
$response = self::request($data, 'http://somesite.com/a/api.php', 'url');
return $response;
}
here is request function
private function request($data, $url, $type) {
$curl = curl_init();
if ($type === 'url') {
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
}
curl_setopt($curl, CURLOPT_URL, $url);
// Force continue-100 from server
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FAILONERROR, 0);
curl_setopt($curl, CURLOPT_CAINFO, __DIR__ . "/cacert.pem");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
if (isset($this->proxyParams['proxy'])) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxyParams['proxy']);
}
$response = json_decode(curl_exec($curl), true);
if ($response === null) {
$response = array (
"success" => false,
"error" => 'cURL Error: ' . curl_error($curl)
);
}
curl_close($curl);
return $response;
}
}
output of echo data is sufficient but its not post and i tried json_decode but nothing is coming to api.php
here is output of echo
{"auth":{"api_key":"be8fgdffgrfffrffc4b3","api_secret":"1b59fsfvfrgfrfvfb29d6e555a1b"},"url":"https:\/\/i.ndtvimg.com\/i\/2017-06\/modi-at-kochi-metro-station_650x400_81497685848.jpg","wait":true}
i tried these in api.php to get the data but nothing is working
$gggss['url'] = json_decode($data, true); //this returns an array
or
$gggss=$_POST['data'];
any help will be great
I think you are trying get urlencoded data, while your JSON string located in body of request. Try use this instead:
$entityBody = file_get_contents('php://input');
I want to call a Google APP Script from PHP in order to create a spreadsheet in a google account enabled in a google developer console. The account has enabled drive API.
This is my PHP script:
require_once '/google_api/autoload.php';
$client_email = 'my-client-email#developer.gserviceaccount.com';
$private_key = file_get_contents('key_file.p12');
$scopes = array('https://www.googleapis.com/auth/bigquery' ,
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/drive',
);
$credentials = new Google_Auth_AssertionCredentials($client_email,
$scopes,
$private_key);
try
{
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$token = $client->getAccessToken();
}
catch(Exception $e)
{
$token = false;
print_r($e);
}
try {
$token = json_decode($token);
} catch (Exception $ex) {
die ('No token');
}
$url = "https://script.google.com/a/macros/myscript-url-details/exec";
$ch = curl_init();
if ($ch)
{
$header = array();
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: Bearer '.$token->access_token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
$curl_output = curl_exec($ch);
if (curl_errno($ch))
{
$curl_error = curl_errno($ch) .": ". curl_error($ch);
}
curl_close($ch);
}
else
{
$curl_output = "Error on Curl";
}
print $curl_output;
Now the APP script is like follow:
function createSheetAndDisplayLink()
{
var spreadsheet = SpreadsheetApp.create('report_1');
var sheet = spreadsheet.getSheets()[0];//insertSheet();
var data = [
['Col1', 'Col2', 'Col3'],
['Field1', 'XXXXX' ,3],
['Field 2', 'XXXXX' ,7]
];
var range = sheet.getRange(1, 1, 3, 3);
range.setValues(data);
url = spreadsheet.getUrl();
return url;
}
function doGet(e)
{
url = createSheetAndDisplayLink();
var content = "Please click on follow link <a href='" + url +"'>Sheet</a>";
var output = ContentService.createTextOutput(content);
return output;
}
I have errors trying to access the APP script.
With follow setting for deploy as web APP:
Execute the app as: Me
Who has access to the app: Only Myself
I got an output from CURL saying that requested File doesn't exist.
If I change the setting to deploy APP as:
Execute the app as: Me
Who has access to the app: "Anyone"
I got output saying that authorization is required.
So it seems like authorization is not being done.
Any help on this will be well of much help.
Thanks!
I am creating a nagios that will automatically login to my website and display result in Nagios. Currenlty I am able to login using script but my PHP Curl script return full HTML code after login thourgh curl.
here is my script.
<?php
$id = "username";
$pw = "password";
$postfields = "userName=farooq&password=hussaind";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1); // Get the header
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Allow redirection
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookie");
curl_setopt($ch, CURLOPT_URL,"http://abc.com/signin.htm");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2) ");
curl_setopt($ch, CURLOPT_POSTFIELDS, "$postfields");
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
# echo $statusCode;
if ($statusCode >= 200) {
echo 'OK - Status Code = '. $statusCode . '. Successfully Login' ;
exit (0);
}
else if ($statusCode >= 400){
echo 'CRITICAL - Status Code = '. $statusCode . '. Unable to loging. Please check ';
exit(2);
}
else {
echo 'UNKOWN - Status Code = '. $statusCode . '. Unable to loging. Please check ';
exit(1);
}
curl_close($ch);
?>
I just want simple message to print without any HTML crap. Like
OK - Status Code = 200 Successfully Login
Please help me in this regard.
Thanks
Farooq Hussain
Set CURLOPT_RETURNTRANSFER to true.
http://www.php.net/manual/en/function.curl-setopt.php