cUrl not returning response - response is BOOL - php

I am trying to verify my recapture with google, but I am getting a response of null
I copy and paste the information to Postman and sent the request and I received a positive response.
I copied the link in my browser as a GET request and I also got a response.
I am not sure what causing this, as all information is correct.
here is my code.
// set API URL
$url = 'https://www.google.com/recaptcha/api/siteverify';
// Collection object
$data = [
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', //<--- my reCaptcha secret key
'response' => $_POST['recaptcha']
];
// Initializes a new cURL session
$curl = curl_init($url);
// Set the CURLOPT_RETURNTRANSFER option to true
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the CURLOPT_POST option to true for POST request
curl_setopt($curl, CURLOPT_POST, true);
// Set the request data as JSON using json_encode function
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
// Execute cURL request with all previous settings
$response = curl_exec($curl);
// Close cURL session
curl_close($curl);
echo 'the response was ' . $response . PHP_EOL;
I saw this but didn't help me. PHP cURL not return a response, POSTMAN returns response

Because it is an HTTPS url you may need to add:
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
It's a good idea to use CURLOPT_FOLLOWLOCATION.
I always use it. It is in my standard options.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
While Google does not return a 302 redirect HTTP status code, they do something funny with the initial request. I made an HTML form and submitted it and a json response was returned but looking at the Browser's headers my initial request disappeared.
I do not think Google wants the post data as JSON.
In the API Request documentation is says METHOD:POST.
It says noting about making the request with JSON.
Google is expecting an array.
Try removing the json_encode().
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
If Google (unlikely) wants a JSON request, you need to add
Content-Type: application/json to the HTTP header.
By adding this header curl will put the "post data" in the body and will not use the
default POST header: application/x-www-form-urlencoded
$request = array();
$request = 'Content-Type: application/json';
curl_setopt($curl, CURLOPT_HTTPHEADER, $request);
I do not understand why there was no response. I would have at least expected:
{
"success": false,
"error-codes": [
"missing-input-secret"
]
}
You may want to add this code after your curl_exec($curl)
This should give you all the details of you request and Google's response.
$response = curl_exec($curl);
$info = rawurldecode(var_export(curl_getinfo($curl),true));
echo "<pre>\n$info<br>\n</pre>";
If you want to see your outgoing request header (recommended) add this option and the header will be in the curl_getinfo:
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
I'm a bit concerned about a NULL being returned. Was the word NULL returned? Or did you see nothing for $response in your string?
curl does not return a NULL. So maybe it was a false. Meaning there is likely a typo. echo does not show boolean false if $response was false you would not see it. Maybe add a
if($response == false){echo "curl failed<br>";}
Even if it failed, all the above is still true.
I looked over your code and I see nothing that would cause curl to fail. Even with the issues, there still should have been some sort of response. And there may have been an HTTP status code that would not show in your $response. It would be in the curl_getinfo

Are you using your local machine in linux? If that so, it is probably because you don't have curl installed in your system. So do
sudo apt install php{version}-curl

Related

Can't validate Slack dialog fields. response_url call always fails

I am trying to build a slack dialog, triggered by a slash command. The dialog pops up correctly, and when the user submits the data, slack hits an endpoints on my server.
From that moment there are two possible outcomes:
Everything is good and I post a confirmation to the user
The data submitted by the user does not pass my app's validation and I need to let the user know.
Let's focus on #2 for a second:
I am getting a response_url that seems valid (https:\/\/hooks.slack.com\/app\/MY-APP-ID\/433197747012\/kQANkbvc3lIViVyLSJKR695z)
For testing, I'd like to simulate a validation error with one of my fields, so I do this in my endpoint:
$errors = [
'errors' => [
[
'name' => 'vendor_email',
'error' => 'sorry, I do not like this dude'
]
]
];
// define the curl request
$ch = curl_init();
// $decoded->response_url does contain the correct slack URL...
curl_setopt($ch, CURLOPT_URL, $decoded->response_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($errors));
// execute curl request
$response = curl_exec($ch);
error_log(" -- response_url response: " . json_encode($response). "\n", 3, './runtime.log');
// close
curl_close($ch);
The response I am getting from hitting the response_url is this:
{\"ok\":false,\"error\":\"invalid_request_data\"}
What am I doing wrong?
****** EDIT ************
Even when not going the CURL route, and just doing this:
return json_encode($errors)
will just close the dialog after submission, and will not trigger any validation error.
The respond_url is not for replying to submissions (e.g. for validation errors), but for sending a message back to the user in the channel.
Once the user completes the dialog you will get a request from Slack. You need to directly respond to that request. You can respond either with an empty response if everything was ok - or with a list of errors for validation. The response must be in JSON and occur within 3 seconds.
To respond all you need to do is echo your error array in JSON. Also make sure to correctly set the header to JSON, like so:
header('Content-Type: application/json');
echo json_encode($errors);
If you have no errors just echo nothing to automatically send a HTTP 200 OK.
See also here in the documentation about how to correctly respond to a submission.

I am getting NULL data in response to cURL request

I am doing a cURL request to fetch information using api but when I use json_decode, it's not giving any information rather it's returning NULL value. Please go through these lines-
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,"http://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.html");
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Is this correct way to make cURL request and fetch information using API, or suggest me how to do as I am new to this topic.
Your following line of code
$result=curl_exec($ch);
returning 301 Moved Permanently
since your URL is use HTTP only
http://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.htm
but this site runs on HTTPS, and server is setup to force/redirect this HTTP only URL to HTTPS i.e.
https://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.html
You can either change your url to https or set follow redirection true using
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirect if any
but still it renders HTML not JSON.
But in your comment you says this same URL is working with node, in such case please cross check your URL or try to make same request using POSTMAN and see what is shows

403 response when sending POST data via cURL

I'm trying to send some data to a custom built API that was built by a web development agency. The api is pretty straight forward, and all that I require to do is authorise myself with an authorisation basic header and submit a payload which is just JSON data.
The problem is that the API is responding with 403 every time I send a POST request using cURL. Is there any way that my code could be causing this? or is it an error that is caused by the API/API server? Regardless if the JSON payload is correctly formatted or not, it should still return with a 200 response.
The request is pretty straight forward -
<?php
//I've removed the actual username and password
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '.base64_encode('username:password'));
$empty_array = array();
//Create empty json as an example
$json = json_encode($empty_array);
$url = "https://website.com/import";
//start cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS,
$json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
If I take out the POST data, then it will return with a 404 response. This is the correct behaviour if there is no POST data submitted to the url. (I get a 404 if I navigate to the url via a browser). So I have a theory that the server must have some kind of restrictions on accepting POST data.
Does my code seem correct or am I missing something glaringly obvious? I wan't to rule out that it's a problem caused by my end due to not being able to access the code/server for the API as that is beyond my control.

Translate CLI request into PHP cURL API request with authorisation string

I've been going round in circles trying to get this bit of code working. The problem I am facing is that there could be any number of places where something is wrong and I'm not experienced enough with cURL and API requests to know if I've just done something simple and silly somewhere. The code below is supposed to fetch a JSON response. What I am currently getting is "false". The API developer keeps giving me a CLI sample and I don't know how to "translate" that into something I can use in PHP.
I have to hide the domain, service name and authentication details in my examples.
The string I was given:
'https://[domain]/agw/latest/services/[service]-api/latest/api/v2/[service]-actual-prizes -vk -H "Proxy-Authorization: Basic [authstr]"'
([authstr] is the username and password, separated by a colon and BASE64 encoded - the API dev has confirmed that my authorisation string is correct)
What I have been trying:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://[domain]/agw/latest/services/lottery-api/latest/api/v2/sportka-actual-prizes');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Proxy-Authorization: Basic '.$authstr.'"
,"Content-type: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
If I understand this correctly (and I'm not sure that I do), then I'm passing the URL (without flags), saying that I don't want a header in the response (I've tried TRUE as well without any success) and then passing headers with my request that includes the authorisation.
I've tried file_get_contents with a stream_context_create header but that fails too.
Am I missing a header option or flag or something in my cURL code?

cURL PHP RESTful service always returning FALSE

I am having some difficulties POSTing a json object to an API that uses REST. I am new to using cURL, but I have searched all over to try to find an answer to my problem but have come up short. My cURL request is always returning false. I know it isn't even posting my json object because I would still get a response from the url. My code is below.
<?php
//API KEY = APIUsername
//API_CODE = APIPassword
$API_Key = "some API key";
$API_Code = "some API code";
$API_email = "email#email.com";
$API_password = "ohhello";
$url = "http://someURL.com/rest.svc/blah";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
header('Content-type: application/json');
$authData = "{\"APIUsername\":\"$API_Key\",\"APIPassword\":\"$API_Code\",\"EmailAddress\":\"$API_email\",\"Password\":\"$API_password\"}";
curl_setopt($ch, CURLOPT_POSTFIELDS, $authData);
//make the request
$result = curl_exec($ch);
$response = json_encode($result);
echo $response;
curl_close()
?>
The $response returns just "false"
Any thoughts?
$response is likely false because curl_exec() returns false (i.e., failure) into $result. Echo out curl_error($ch) (after the call to curl_exec) to see the cURL error, if that's the problem.
On a different note, I think your CURLOPT_POSTFIELDS is in an invalid format. You don't pass a JSON string to that.
This parameter can either be passed as
a urlencoded string like
'para1=val1&para2=val2&...' or as an
array with the field name as key and
field data as value.
-- PHP docs for curl_setopt()
Update
The quick way to avoid the SSL error is to add this option:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
You get an SSL verification error because cURL, unlike browsers, does not have a preloaded list of trusted certificate authorities (CAs), so no SSL certificates are trusted by default. The quick solution is to just accept certificates without verification by using the line above. The better solution is to manually add only the certificate(s) or CA(s) you want to accept. See this article on cURL and SSL for more information.

Categories