curl error,troubleshoot json/php error - php

cURL Error (28): Operation timed out after 201 milliseconds with 0 bytes received
Here is my code:
if (!isset($_GET['foo'])) {
// Client
$pIds = array("All");
$data = array("apiToken" => "apitoken-3D", "productIds" => $pIds);
$data_string = json_encode($data);
//echo $data_string;
$ch = curl_init('http://myurl/WriteProductData');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$data = curl_exec($ch);
//var_dump(json_decode($data, true));
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_error\n";
} else {
echo "Data received: $data\n";
} else {
// Server
sleep(10);
echo "Done.";
}
Above is not the real API key, etc. but just wanted you to see the code.
Please advise how to troubleshoot this, and what to do to resolve this issue. We can make adjustments on the server if necessary.

Related

Stop foreach loop when curl return 200

I try to communicate with my Proxmox cluster which contain 3 servers, from API. Goal is to connect to at least 1 of these servers in case of failure then execute other code (not visible here).
With the below code, I connect to these servers 1 by 1 using "foreach" and I want this loop stop when one server return "200" from Curl (so I can continue with this online server). For the test, I stopped the first server and let online the others 2 but the "foreach" loop keep connect the third server.
Any idea ? Thank you and sorry for my english.
<?php
$datas = array(
array(
"apiurl" => "192.168.1.34:8006",
"node" => "pve1",
"user" => "root",
"userpass" => "pass",
),
array(
"apiurl" => "192.168.1.35:8006",
"node" => "pve2",
"user" => "root",
"userpass" => "pass",
),
array(
"apiurl" => "192.168.1.36:8006",
"node" => "pve3",
"user" => "root",
"userpass" => "pass",
)
);
do {
foreach ($datas as $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'#pam&password='.$data['userpass']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
}
else {
$myArray = json_decode($result, true);
$cookie = $myArray['data']['ticket'];
$info = curl_getinfo($ch);
echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
}
curl_close($ch);
}
} while ($info['http_code'] !== 200);
?>
You can break out of an outer loop by giving an argument to break. break 2 means to break out of the second containing loop.
while (true) {
foreach ($datas as $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'#pam&password='.$data['userpass']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
}
else {
$myArray = json_decode($result, true);
$cookie = $myArray['data']['ticket'];
$info = curl_getinfo($ch);
echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
if ($info['http_code'] == 200) {
break 2;
}
}
curl_close($ch);
}
}
What you have here is an infinite loop, because as you stated you already know the last 2 servers in the array won't respond successfully, yet your foreach loop will try all 3 regardless of success or failure. So by the time you get to the 3rd iteration of the foreach loop you get a failed response and then you reach the end of the while loop which determines the condition is still true and continues. To prevent this simply break from the foreach loop once success is determined. Because only then will the condition of the while loop become false. You can also break out of both loops if you'd like (using break 2). Either one is correct. The only difference is if you wanted any remaining logic inside the outter (while) loop to happen regardless of success or failure.
foreach ($datas as $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'#pam&password='.$data['userpass']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
}
else {
$myArray = json_decode($result, true);
$cookie = $myArray['data']['ticket'];
$info = curl_getinfo($ch);
echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
if (!empty($info['http_code']) && $info['http_code'] == 200) {
break; // break out of either or both loops since we got a valid response
}
}
curl_close($ch);
}

Curl Post using PHP

This is mi First Post on Stackoverflow.
I need to do a Curl Post to an SMS Gateway with PHP but I´d never done it, the manual says I should do something like this
curl -u admin:admin -d '{"text":"Hello.","port":[0],"param":[{"number":"123456","text_param":["John"],"user_id":1}]}’ –H "Content-Type:
application/json" http://192.168.1.252/api/send_sms
#I tried some users post, but I can´t get to get it working.
<?php
$ch = curl_init();
$username='admin';
$password='admin';
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_URL,"http://192.168.1.252/api/send_sms");
curl_setopt($ch, CURLOPT_POST, 1);
$data = array(
'text' => "TEXT TO BE SEND",
'port' => 0,
'number'=>"123456",
'text_param'=>"John",
'user_id'=>1
);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
#Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
$errno = curl_errno($ch);
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
curl_close ($ch);
#Further processing ...
if ($server_output == "OK") { echo "OK"; } else { echo "FAILED"; }
?>
Solved it,
Thanks a lot anyway. I added content type with
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json'));
and redone the $data to meat specs.
Thanks

Wowza Cloud API: curl requests

I can't make it work.. :( I have this function (for create passthrough transcoder), when I run I see NULL in the web. If I test directly from the browser with the url, it does notify me that there is a problem an auth (apikey and acceskey)
function createPassthrough($name, $source_url, $recording = null)
{
$url = "https://sandbox.cloud.wowza.com/api/v1/transcoders";
$json = '{
"transcoder":{
"billing_mode":"pay_as_you_go",
"broadcast_location":"eu_belgium",
"delivery_method":"pull",
"name":"prueba",
"protocol":"rtsp",
"source_url":"url_camara",
"transcoder_Type":"passthrough",
"low_latency":true,
"buffer_size":0,
"play_maximum_connections":100,
"stream_smoother":false
}
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-Type: application/json; charset=utf-8',
'wsc-api-key:' . $apiKey,
'wsc-access-key:' . $accessKey,
));
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj);
}
What am I doing wrong? Thanks in advance.
You should check for curl errors after $result = curl_exec($ch);.
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}

Getting error while sending http request via curl

I want to send charging request through php which I have sent via postman and it worked, but when I try this with php I m getting error response.
I have tried to send the request using curl and used function to send the request. But, after hitting the php I m getting the response that "invalid request" .
Here is the code snippet:
<?php
define('TML_CHARGE_URL2', 'http://sandbox-apigw.mytelenor.com.mm/v1/mm/en/customers/products/vas');
$client_id="MDq0MdGtZUGZWfanE8k2fva7GsLvwS0I";
$client_secret="GEzAxTE6YYSfLEAD";
$accessToken="ytSxhvjSUfNEurD5M6SOJPm6XAfu";
/* CP & Product Codes */
$cpid="15";
$login="apigwtest";
$password="apigwtestpwd";
$client_id="175612092873562378";
$msisdn="9791000601";
$prod_code = "APIGW_TEST";
$requestParamList = array("cpID" => $cpid,
"clientTransactionId" => $client_id,
"loginName" => $login,
"password" => $password,
"id" => array (
"type" => "MSISDN",
"value" => $msisdn
),
"productCode" => $prod_code
);
function callAPI($apiURL, $requestParamList) {
$jsonResponse = "";
$responseParamList = array();
$JsonData =json_encode($requestParamList);
$postData = 'JsonData='.urlencode($JsonData);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}
function oneshotpayment($requestParamList) {
return callAPI(TML_CHARGE_URL, $requestParamList);
}
function subscription_payment($requestParamList) {
return callAPI(TML_CHARGE_URL2, $requestParamList);
}
echo subscription_payment($requestParamList);
?>
The error response is like below:
{
"transactionId": "",
"timestamp": "2017-08-13T17:28:24+06:30",
"recipientMsisdn": "",
"code": "500.023.003",
"error": "Internal Server Error",
"message": "Request input is malformed or invalid"
}
You need to change your callAPI method.
1) You dont need to do urlencode after you have done json_encode
2) Remove unnecessory concatination of 'JsonData='. in string.
change you method like below
function callAPI($apiURL, $requestParamList) {
$postData = "";
$responseParamList = array();
$postData =json_encode($requestParamList);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}

Terminate function a() when function b() failed

We are a little bit confuse how we can achieve this problem. We don't want to run the createsite function in our code if createSubaccount function fails. We would truly appreciate any feedbacks, comments, guides on our code.
<?php
//Set API user and password
define("API_USER","user");
define("API_PASS","pw");
$createdSite = createSite($_REQUEST['template_id'],$_REQUEST['original_url']);
//echo 'Site Created: ' . $createdSite . '<br/>';
$accountCreated = createSubAccount($_REQUEST['email']);//client email
//echo 'Account created: ' . $accountCreated . '<br/>';
$first_name = $_REQUEST['first_name'];//First Name
$last_name = $_REQUEST['last_name'];//Last Name
$retArr = ["sso"=>$sso_link,"ru"=>$resetURL,"ac"=>$accountCreated,"fn"=>$first_name,"ln"=>$last_name];//assoc array
print json_encode ($retArr);//json string
function createSite($template_id,$original_url) {
//create array with data
if($original_url) {
$data = array("template_id"=>$_REQUEST['template_id'],"url"=>$original_url);
} else {
$data = array("template_id"=>$_REQUEST['template_id']);
}
//turn data into json to pass via cURL
$data = json_encode($data);
//Set cURL parameters
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/api/create');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, API_USER.':'.API_PASS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//execute cURL call and get template data
$output = curl_exec($ch);
//check for errors in cURL
if(curl_errno($ch)) {
die('Curl error: ' . curl_error($ch));
}
$output = json_decode($output);
return $output->site_name;//Output /Return : {"site_name":"28e1182c"}
}
function createSubAccount($emailToCreate) {
$first_name = $_REQUEST['first_name'];//First Name
$last_name = $_REQUEST['last_name'];//Last Name
$data = '{"account_name":"'.$emailToCreate.'", "first_name":"'.$first_name.'", "last_name":"'.$last_name.'"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/api/create');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, API_USER.':'.API_PASS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//execute cURL call and get template data
$output = curl_exec($ch);
if(curl_getinfo($ch,CURLINFO_HTTP_CODE) == 204) {
curl_close($ch);
return $emailToCreate;//Expected return HTTP Code: 204 No Content
} else {
curl_close($ch);
$output = 'failed';
return $output;
die('Account creation failed, error: '. $output . '<br/>');
}
}
?>
This is where an Exception comes in handy.
function createSite() {
throw new \Exception('Failed');
}
try {
$createdSite = createSite($_REQUEST['template_id'],$_REQUEST['original_url']);
//echo 'Site Created: ' . $createdSite . '<br/>';
$accountCreated = createSubAccount($_REQUEST['email']);//client email
} catch(\Exception $err) {
echo $err->getMessage();
}
The Exception prevents the rest of the code in the block from executing once thrown.

Categories