How Do i translate command line curl commang into PHP curl call? - php

Here is the command line command:
curl -H "Authorization: Bearer API_KEY" -X PUT https://graph.api.smartthings.com/api/smartapps/installations/DEVICE_ID/lock
Here is what i have uptill now, what is wrong with this code:
$headers = array('Authorization: Bearer ' . $st_api_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$response = curl_exec($ch);
curl_close($ch);
Output for var_dump(curl_getinfo($ch)); is, I am still unable to find the real error or i am doing something wrong in translating this code to PHP:
<?php array (size=26)
url => string 'https://graph.api.smartthings.com/api/smartapps/installations/c8137097-8532-43b8-b516-0573cb91ecee/setLockCode/20/3333' (length=118)
'content_type' => null
'http_code' => int 0
'header_size' => int 0
'request_size' => int 0
'filetime' => int -1
'ssl_verify_result' => int 1
'redirect_count' => int 0
'total_time' => float 0.547
'namelookup_time' => float 0
'connect_time' => float 0.282
'pretransfer_time' => float 0
'size_upload' => float 0
'size_download' => float 0
'speed_download' => float 0
'speed_upload' => float 0
'download_content_length' => float -1
'upload_content_length' => float -1
'starttransfer_time' => float 0
'redirect_time' => float 0
'redirect_url' => string '' (length=0)
'primary_ip' => string '54.243.113.196' (length=14)
'certinfo' =>
array (size=0)
empty
'primary_port' => int 443
'local_ip' => string '192.168.0.139' (length=13)
'local_port' => int 62555
?>

After searching on internet i got this issue fixed by changing headers array and adding curl settings:
$headers = array('Authorization: Bearer ' . $st_api_token,
'Content-Type: application/json',
'Accept: json',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

Related

PHP cURL not aible to show response

<?php
$ch = curl_init();
//$concept_id = $_POST['concept_id'];
curl_setopt($ch, CURLOPT_URL, "https://browser.ihtsdotools.org/snowstorm/snomed-ct/browser/MAIN/2022-03-31/concepts/84114007");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded'));
$response = curl_exec($ch);
//echo curl_error($ch);
//echo '<p>';
//echo curl_errno($ch);
//echo '<p>';
$info = rawurldecode(var_export(curl_getinfo($ch),true));
curl_close($ch);
echo "<pre>\n$info<br>\n</pre>";
var_dump ($response);
?>
I am not able to retrieve the response of the SNOMED API. Works with my browser with the same URL.
I received no error message, just an empty response.
Tried to add these parameters without change :
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Here the response:
array (
'url' => 'https://browser.ihtsdotools.org/snowstorm/snomed-ct/browser/MAIN/2022-03-31/concepts/84114007',
'content_type' => NULL,
'http_code' => 423,
'header_size' => 112,
'request_size' => 123,
'filetime' => -1,
'ssl_verify_result' => 0,
'redirect_count' => 0,
'total_time' => 0.61424600000000007,
'namelookup_time' => 0.052975000000000001,
'connect_time' => 0.15305099999999999,
'pretransfer_time' => 0.51591100000000001,
'size_upload' => 0.0,
'size_download' => 0.0,
'speed_download' => 0.0,
'speed_upload' => 0.0,
'download_content_length' => 0.0,
'upload_content_length' => 0.0,
'starttransfer_time' => 0.61422100000000002,
'redirect_time' => 0.0,
'redirect_url' => '',
'primary_ip' => '3.225.65.37',
'certinfo' =>
array (
),
'primary_port' => 443,
'local_ip' => '10.102.1.146',
'local_port' => 41662,
)
string(0) ""
When we look for information on the 423 code returned, we see that sometimes pages are blocked because the client is not an Internet browser
So if we simulate an internet explorer with the "Agent" parameter, it works
Normally the code below should help you
// Determinate URL
$urlTest = "https://browser.ihtsdotools.org/snowstorm/snomed-ct/browser/MAIN/2022-03-31/concepts/84114007";
// Initialization Session CURL
$curlObject = #curl_init();
// Simulation of Agent
$config['useragent'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';
// Définition Options de la Session CURL
curl_setopt($curlObject, CURLOPT_USERAGENT, $config['useragent']);
curl_setopt($curlObject, CURLOPT_VERBOSE, false);
curl_setopt($curlObject, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlObject, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObject, CURLOPT_CONNECTTIMEOUT, 600);
curl_setopt($curlObject, CURLOPT_URL,$urlTest);
// Running Session CURL
$curlResponse = #curl_exec($curlObject);
// If successful execution
if($curlResponse!=false)
{
$dataList = json_decode($curlResponse, true); echo "<pre>"; print_r($dataList); echo "</pre>";
}
else echo "Error Connexion CURL - [".curl_errno($curlObject)."] ".curl_error($curlObject);

Unexpected 401 response when calling haveibeenpwned API

I dead stuck on an 401 response, another user suggested my header didn't included a leading white space for the API key field. I corrected it and am still receiving a 401. The API key should work, I paid for it last night, and regenerated a new one multiple times
my code:
<?php
$service_url = 'https://haveibeenpwned.com/api/v3/breachedaccount/?account=emailtest123#gmail.com';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$ch = curl_init ($service_url);
curl_setopt ($ch, CURLOPT_HTTPGET, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'hibp-api-key: 8bcxxxxxxxxxxxxxx1bc11',
'user-agent: FAUstudentproject'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$returndata = curl_exec ($ch);
$status_code = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
print_r($status_code);
print_r($returndata);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
$json = curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded1 = json_decode($curl_response,true);
if (isset($decoded1->response->status) && $decoded1->response->status == 'ERROR') {
echo "hello";
echo curl_getinfo($ch);
die('error occured: ' . $decoded1->response->errormessage);
}
echo 'response ok!';
print_r(json_decode($json));
var_export($decoded1->response);
?>
The response:
401{ "statusCode": 401, "message": "Access denied due to missing hibp-api-key." }array ( 'url' => 'https://haveibeenpwned.com/api/v3/breachedaccount/?account=emailtest123#gmail.com', 'content_type' => NULL, 'http_code' => 0, 'header_size' => 0, 'request_size' => 0, 'filetime' => -1, 'ssl_verify_result' => 20, 'redirect_count' => 0, 'total_time' => 0.04700000000000000011102230246251565404236316680908203125, 'namelookup_time' => 0.01600000000000000033306690738754696212708950042724609375, 'connect_time' => 0.0309999999999999997779553950749686919152736663818359375, 'pretransfer_time' => 0.0, 'size_upload' => 0.0, 'size_download' => 0.0, 'speed_download' => 0.0, 'speed_upload' => 0.0, 'download_content_length' => -1.0, 'upload_content_length' => -1.0, 'starttransfer_time' => 0.0, 'redirect_time' => 0.0, 'redirect_url' => '', 'primary_ip' => '2606:4700::6812:ad0d', 'certinfo' => array ( ), 'primary_port' => 443, 'local_ip' => '2601xxxxxxxxxxxxxxxxx21d3', 'local_port' => 59096, 'http_version' => 0, 'protocol' => 2, 'ssl_verifyresult' => 0, 'scheme' => 'HTTPS', )error occured during curl exec. Additioanl info:
You are using the wrong variable: replace curl_setopt($curl, CURLOPT_HTTPHEADER with curl_setopt($ch, CURLOPT_HTTPHEADER. You're using curl_init twice in your code.
Check your code to fix it, using only $ch or $curl, not both.

I can not post data using PHP

I used this code but I get always empty result I don't know why
if (isset($_POST['uname'], $_POST['password'])){
$uname = test_input($_POST['uname']);
$pw = test_input($_POST['password']);
$data = array(
"loginEmail" => $uname,
"loginPassword" => $pw,
"clientURI" => "https://hk2.notify.windows.com/?token=AwYAAAC2bng45wHDpXWajWLTxGM1gxP1DcLlHTL8%2bhOfKVbkpYjl1U9tnUGrW4FSmwuiiWPKEyvSUoO5v9nfzFWZ097kdUeN8xDpAlp96Ilk3LCSN0sQNFuyU%3d"
);
$url_send ="https://dev-frontserver.com/api/login";
$str_data = json_encode($data);
$headers = array("Content-Type: application/json");
function sendPostData($url, $post, $headers){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
echo "result = " .sendPostData($url_send, $str_data, $headers);*/
}
Any idea what is wrong with my code ? I tried the api in https://www.hurl.it and it work but I can not get it to work in my code.
Here are the returned data from `curl_getinfo($ch);'
array (size=26)
'url' => string 'https://dev-fronapp.com/api/login' (length=47)
'content_type' => string 'application/json; charset=utf-8' (length=31)
'http_code' => int 200
'header_size' => int 268
'request_size' => int 384
'filetime' => int -1
'ssl_verify_result' => int 20
'redirect_count' => int 0
'total_time' => float 2.14
'namelookup_time' => float 0
'connect_time' => float 0.344
'pretransfer_time' => float 1.047
'size_upload' => float 253
'size_download' => float 3991
'speed_download' => float 1864
'speed_upload' => float 118
'download_content_length' => float 3991
'upload_content_length' => float 253
'starttransfer_time' => float 2.125
'redirect_time' => float 0
'redirect_url' => string '' (length=0)
'primary_ip' => string '' (length=13)
'certinfo' =>
array (size=0)
empty
'primary_port' => int 443
'local_ip' => string '' (length=12)
'local_port' => int 10484
Your modify code and changes made are
CURL SSL verifier is set to false
JSON error handling
API runtime exceptions
return values if api status is 1/200/ok/true.
<?php
if (isset($_POST['uname'], $_POST['password'])){
$uname = test_input($_POST['uname']);
$pw = test_input($_POST['password']);
$data = array(
"loginEmail" => $uname,
"loginPassword" => $pw,
"clientURI" => "https://hk2.notify.windows.com/?token=AwYAAAC2bng45wHDpXWajWLTxGM1gxP1DcLlHTL8%2bhOfKVbkpYjl1U9tnUGrW4FSmwuiiWPKEyvSUoO5v9nfzFWZ097kdUeN8xDpAlp96Ilk3LCSN0sQNFuyU%3d"
);
$url_send ="https://dev-frontserver.com/api/login";
$str_data = json_encode($data);
$headers = array("Content-Type: application/json");
echo "result = " .sendPostData($url_send, $str_data, $headers);
}
function sendPostData($url, $post, $headers){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));
//avoid checking ssl verifier
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
$result = curl_exec($ch);
if($result === false) {
throw new \RuntimeException(
'API call failed with cURL error: ' . curl_error($ch)
);
}
curl_close($ch);
$apiResponse = json_decode($result, true);
// Make sure we got back a well-formed JSON string and that there were no errors when decoding it
$jsonError = json_last_error();
if($jsonError !== JSON_ERROR_NONE) {
throw new \RuntimeException(
'API response not well-formed (json error code: ' . $jsonError . ')'
);
}
// Print out the response details
if($apiResponse['status'] === 1)//check field where
{
// No errors encountered
return $result;
}
else {
// An error occurred
die("Error:");//show error message from api
}
}
?>
Please test code and let me know if any modifications needed

getting data with curl failed

I'm trying to get the data returned from this link with CURL. However, I'm getting false as the output.
Here's my code and output:
Code:
$url = "https://airport.api.aero/airport/distance/LOS/ABV?user_key=MY_USER_KEY_GOES_HERE&units=mile";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
var_dump( curl_getinfo($ch) );
curl_close($ch);
var_dump($data);
Dump of curl_getinfo call
array (size=26)
'url' => string 'https://airport.api.aero/airport/distance/LOS/ABV?user_key=MY_USER_KEY&units=mile' (length=102)
'content_type' => null
'http_code' => int 0
'header_size' => int 0
'request_size' => int 0
'filetime' => int -1
'ssl_verify_result' => int 0
'redirect_count' => int 0
'total_time' => float 0.702
'namelookup_time' => float 0.249
'connect_time' => float 0.468
'pretransfer_time' => float 0
'size_upload' => float 0
'size_download' => float 0
'speed_download' => float 0
'speed_upload' => float 0
'download_content_length' => float -1
'upload_content_length' => float -1
'starttransfer_time' => float 0
'redirect_time' => float 0
'redirect_url' => string '' (length=0)
'primary_ip' => string '107.22.197.175' (length=14)
'certinfo' =>
array (size=0)
empty
'primary_port' => int 443
'local_ip' => string '192.168.1.17' (length=12)
'local_port' => int 53767
Dump of $data
boolean false
Is there something I'm doing wrong?
I was able to successfully send a get request (you should hide your key from your question lol)
Try this:
$url = "https://airport.api.aero/airport/distance/LOS/ABV";
$qry_str = "?units=mile&user_key=MY_USER_KEY_GOES_HERE";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $qry_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_HEADER, 0);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
Found the solution here. Since the url was using https, I needed to include this option curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);. That did it.
Are you able to make a curl request via command line?
i.e curl 'https://airport.api.aero/airport/distance/LOS/ABV?user_key=MY_USER_KEY_GOES_HERE&units=mile'

Freebase API works in browser but not in PHP

This question is similar to: Freebase API call works in browser but fails with curl but no answers there.
I have this URL that works in the browser:
https://www.googleapis.com/freebase/v1/search?query=Cee+Lo+Green&filter=%28all+type%3A%2Fmusic%2Fartist+created%3A%22The+Lady+Killer%22%29&limit=10&key=my_key_here
Returns:
{"status":"200 OK","result":[{"mid":"/m/01w5jwb","id":"/en/cee_lo_1974","name":"Cee Lo Green","notable":{"name":"Singer-songwriter","id":"/m/016z4k"},"lang":"en","score":814.733643}],"cost":6,"hits":2}
However, in PHP, the following code doesn't work:
<?php
namespace com\voting;
class Freebase{
public function query(){
$service_url = 'https://www.googleapis.com/freebase/v1/search';
$params = array(
'query' => 'Cee Lo Green',
'filter' => '(all type:/music/artist created:"The Lady Killer")',
'limit' => 10,
'key' => API_KEY );
$url = $service_url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response;
}
}
?>
A dump of curl, gives this:
array (size=22)
'url' => string 'https://www.googleapis.com/freebase/v1/search?query=Cee+Lo+Green&filter=%28all+type%3A%2Fmusic%2Fartist+created%3A%22The+Lady+Killer%22%29&limit=10&key=my_key_here' (length=191)
'content_type' => null
'http_code' => int 0
'header_size' => int 0
'request_size' => int 0
'filetime' => int -1
'ssl_verify_result' => int 0
'redirect_count' => int 0
'total_time' => float 0.047
'namelookup_time' => float 0
'connect_time' => float 0.063
'pretransfer_time' => float 0
'size_upload' => float 0
'size_download' => float 0
'speed_download' => float 0
'speed_upload' => float 0
'download_content_length' => float -1
'upload_content_length' => float -1
'starttransfer_time' => float 0
'redirect_time' => float 0
'certinfo' =>
array (size=0)
empty
'redirect_url' => string '' (length=0)
I thought maybe a connectivity issue, but I tried a regular http URL and curl showed that it was able to get the content of the page.
Update 1
I should have done my homework before posting. With Wireshark, I can see the following text:
Alert Message
Level: Fatal (2)
Description: Unknown CA (48)
Is my setup improperly configured?
Thanks, in just a script:
<?php
$service_url = 'https://www.googleapis.com/freebase/v1/search';
$params = array(
'query' => 'Cee Lo Green',
'filter' => '(all type:/music/artist created:"The Lady Killer")',
'limit' => 10,
'key' => API_KEY );
$url = $service_url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//WARNING: this would prevent curl from detecting a 'man in the middle' attack
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response;
?>
This answer solved it for me:
HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK
Final solution:
<?php
namespace com\voting;
class Freebase{
public function query(){
$service_url = 'https://www.googleapis.com/freebase/v1/search';
$params = array(
'query' => 'Cee Lo Green',
'filter' => '(all type:/music/artist created:"The Lady Killer")',
'limit' => 10,
'key' => API_KEY );
$url = $service_url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//WARNING: this would prevent curl from detecting a 'man in the middle' attack
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response;
}
}
?>

Categories