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¶2=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.
Related
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
My Deepcrawl crawl only give null value.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.deepcrawl.com/accounts/00000/projects/195334/crawls/1306396/reports/thin_pages_basic");
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Auth-Token:Private'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output2 = curl_exec ($ch);
curl_close ($ch);
$results = json_decode($server_output2);
To create a session you first need to manually generate an API Key. This is a key/value pair that can be generated in the API Access page. When you click Generate New API Key, a popup will be displayed with the API Key Value and in the table of Active Keys you can find the API Key ID. This is then sent via Basic Authentication in a POST call to the sessions route.
curl -X POST -u '123:abcdef' https://api.deepcrawl.com/sessions
{
"token":"abcdef123",
"_user_href":"/users/example-user",
...
}
The token returned from the call to sessions is then passed to all API calls as the X-Auth-Token header:
curl -X GET -H 'X-Auth-Token:' https://api.deepcrawl.com/accounts/1/projects
Can someone explain me further about the authentication of deepcrawl? How can I able to curl it using X-Auth-Token only. Sorry for my bad English. Thank you
CURL may be tricky sometimes.
When I face problems with CURL I first try to do the same on command line, in this case it worked perfectly so we can reject there is any kind of problem on API or on CURL so we must assume the problem is on the php call.
When you get a NULL it's likely there is an error set on curl handler, you just need to look for it and bring it to screen:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.deepcrawl.com/accounts/00000/projects/195334/crawls/1306396/reports/thin_pages_basic");
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Auth-Token:Private'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output2 = curl_exec ($ch);
if (curl_errno($ch)) {
print curl_error($ch);
die();
// or whatever you might want to do with this error
}
curl_close ($ch);
$results = json_decode($server_output2);
In this case the error was:
SSL certificate problem: unable to get local issuer certificate
Here you can see how to fix this problem, just need to add a valid CA cert to your php.ini (in the example cacert is used) like that:
1) Download the latest cacert.pem from https://curl.haxx.se/ca/cacert.pem
2) Add the following line to php.ini (if this is shared hosting and you don't have access to php.ini then you could add this to .user.ini in public_html)
curl.cainfo="/path/to/downloaded/cacert.pem"
I am working with rest API. I am using zoho API's for making calls. Working in yii2 I am trying to call a GET API which gives me some details about my project.
/* Set the Request Url (without Parameters) here */
$request_url = 'https://projectsapi.zoho.com/restapi/portal/[PORTALID]/projects/[PROJECTID]/bugs/defaultfields/';
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authtoken' => 'key')); // here i am using key but in actual i am putting the real key value
$curl_response = curl_exec($ch);
$json = json_decode($curl_response);
var_dump($json);
exit();
Accessing it via POSTMAN when I run this call it gives me NULL in response. I have also tried out the way mentioned in the PHP Example here. But it doesn't work out for me as well.
I must be missing something that I don't know.
Any help would be highly appreciated.
Try checking your headers and make sure you're passing through all the required fields for an example authorization, content type etc.
I get a response via my localhost Wampserver from Paypal mobile SDK. I receive a string via a cURL call. This string has been verified to be in json form via the online service Json Lint website. I was able to convert the json string to an array in php code, using an online php compiler, phptester.net using php version 5.5. However, when i tried the same code on my wampserver it says that the array size equals zero. I don't know what could be wrong. Please help me evaluate my PHP code.
Here's the response from Paypal mobile sdk:
{"scope":"https://uri.paypal.com/services/subscriptions https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/applications/webhooks openid https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.*","nonce":"2016-03-06T22:13:44ZNxK118Mc40QthTeJX8Y_enneSe0y62kEo6mu0ICCwMU","access_token":"A101.ONfkNw-H4-VcjWL9ZUbLlaDj1YUApO7X9fhOslMKRLyW1JpKL1hLlD5W2m9xri-y.ZRF-23gpYMDQ5vWPkOsEiv8WbJC","token_type":"Bearer","app_id":"APP-80W284485P519543T","expires_in":32399}
Here's the relevant code i use in my php file:
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $idclient.":".$sekret);
$result = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);
echo $result;
$arr = (array) json_decode($result);
$token = $arr['access_token'];
echo "here's the token oken";
var_dump($arr);
var_dump($token);
Here's the code i use in phptester.net:
$e ='I copied and paste the response i get from server here. noticed the
single quotes here. Maybe this is the problem';
$a = (array)json_decode($e);
$b = $a['access_token'];
var_dump($b);
this code accurately prints out the value of the array at "access_token', which is the access_token i need to verify payments made to PayPal.
I need to replicate this good code on my Wamp server php file. But it is not doing what is supposed to. It says the size of my array is zero, and that the variable $token is null. Please help me in evaluating my code.
Thank you
Try this, don't try to cast json_decode to array. you can use second option in json_decode to convert it to associative arrays.
PHP Doc
$e ='{"scope":"https://uri.paypal.com/services/subscriptions https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/applications/webhooks openid https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.*","nonce":"2016-03-06T22:13:44ZNxK118Mc40QthTeJX8Y_enneSe0y62kEo6mu0ICCwMU","access_token":"A101.ONfkNw-H4-VcjWL9ZUbLlaDj1YUApO7X9fhOslMKRLyW1JpKL1hLlD5W2m9xri-y.ZRF-23gpYMDQ5vWPkOsEiv8WbJC","token_type":"Bearer","app_id":"APP-80W284485P519543T","expires_in":32399}';
$a = json_decode($e,true);
$b = $a['access_token'];
var_dump($b);
here
I was able to find the answer to my problem. I just had to get rid of the header which was returned in the returned string from PayPal. I did this by setting the following cURL option to false: curl_setopt($ch,CURLOPT_HEADER,true)
Then, I was able to use json_decode() on the returned string to convert it to an array, which allowed me to access the access_token index field in the array.
Now, I just need to store this string on my online database for purchase verification via PayPal mobile SDK.
I want to add the HTTP headers for authenticating Udemy API access.Can someone tell me as to how to add the headers.I already have the client id and secret key.I want to access the API from a PHP page.
https://developers.udemy.com/
Here is the code i tried using:
$ch = curl_init($request);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id:MY_ID','X-Udemy-Client-Secret:Secret'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$results= curl_exec($ch);
echo $results;
Output:
Blank Page
Can someone point out what the problem might be?
As #drmarvelous wrote, you perform two requests (1st - by CURL, and 2nd - by file_get_contents) which does the same. Wherein the result of CURL request is not actually used in your script. It use the result of file_get_contents request which is performed without authentication parameters. Because of this you getting Unauthorized error.
So you have to use the result of CURL request:
...
$json = json_decode($results, true);
print_r($json);
Update:
You have to ensure you use valid URL for API request, i.e. value of $request in your code should be valid URL. Also, ensure you pass valid authentication parameters (Client-Id and Client-Secret) by HTTP headers.
Furthermore, since API is secured, you have to disable SSL peer verification by setting CURLOPT_SSL_VERIFYPEER option to false.
So the code should look like this:
$ch = curl_init($request);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: {YourID}','X-Udemy-Client-Secret: {YourSecret}'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$results= curl_exec($ch);
echo $results;