I have curl code here:
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'http://steamcommunity.com/profiles/' . $user->steam_id . '/inventory/json/730/2/');
$d=curl_exec($ch);
curl_close($ch);
Sometimes the URL gives me just null response. Is there anything possible to do, if it does that, then it will do the request again?
Regards
You could use the retry package. It's just one function:
function retry($retries, callable $fn)
{
beginning:
try {
return $fn();
} catch (\Exception $e) {
if (!$retries) {
throw $e;
}
$retries--;
goto beginning;
}
}
You can use it like this:
// retry an operation up to 3 times
$response = retry(3, function () use ($user) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'http://steamcommunity.com/profiles/' . $user->steam_id . '/inventory/json/730/2/');
if (!$response = curl_exec($ch)) {
throw new RuntimeException(curl_error($ch));
}
curl_close($ch);
return $response;
});
Related
I am working on some code on PHP that allow me to get json data from an api.
so
1 typical URL is not providing the data no matter what. when checking for empty in the $result, it says it has value in it, but when required to print it does not print or echo. This same URL when tested in PostMan works and provide data.
The strange part is the data are in the same format and
all other URLs calls work fine both on PostMan and through the code below.
I was able to trace to here and I am suspecting something is wrong with the "curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);" or the "curl_exec". the rest I am stuck!
All URL data return are similar and same format in PostMan.
No error returns.
function getRestCall($url, $data = null, $method = self::METHOD_GET)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
printf('<h2>URL</h2>' . $url);
// Set authentication parameters
curl_setopt($curl, CURLOPT_USERPWD, $this->username . ':' . $this->password);
// Don't send as json when attaching files to tasks.
if (is_string($data) || empty($data['file']))
{
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'content-Type: application/json'
)); // Send as JSON
}
// Dont print result
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set maximum timeout limit
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->timeout);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
// Don't verify SSL connection
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
// Define methods
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
if ($method == self::METHOD_POST)
{
curl_setopt($curl, CURLOPT_POST, true);
}
elseif ($method == self::METHOD_PUT)
{
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
}
elseif ($method == self::METHOD_DELETE)
{
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
// Define post data if we have the correct method
if (!is_null($data) && ($method == self::METHOD_POST || $method == self::METHOD_PUT))
{
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
try
{
$return = curl_exec($curl);
if ($this->debug)
{
$info = curl_getinfo($curl);
echo '<pre>';
print_r($info);
echo '</pre>';
if ($info['http_code'] == 0)
{
echo '<br />error num: ' . curl_errno($curl);
echo '<br />error: ' . curl_error($curl);
}
if (!is_null($data))
{
echo '<br />Sent info:<br /><pre>';
print_r($data);
echo '</pre>';
}
}
}
catch(Exception $e)
{
$return = null;
if ($this->debug)
{
echo "Exception caught: " . $e->getMessage();
}
}
if ($return === false)
{
printf('<h2>Return value is error, SHOW!!: </h2>');
$return = curl_error($curl);
//printf('<h2>Return value is not empty, SHOW!!: </h2>'. $return);
}else
{
printf('<h2>no error</h2>');
}
curl_close($curl);
return $return;
}
I am suspecting something is wrong with the "curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);" or the "curl_exec".
i have this question, i try to send a request to one API, this APPI expect an application/json so i first test in postman to see the results and works as i expected, but in my code no, next my code,
public function myfunctiion()
{
$req = '{
"myparams": myvalues,
"myparams": myvalues,
"myparams": myvalues,
"myparams": {
"myparams": myvalues,
"myparams": "myvalues",
"myparams": "myvalues",
"myparams": myvalues
}';
$jsonRequest = json_decode($req, TRUE); ;
try{
self::setWsdl('API url');
$context =[
'Content-Type: application/json',
'Accept: application/json',
];
self::setContext($context);
self::setRequest($jsonRequest);
return InstanceCurlClient::curlClientInit();
} catch(\Exception $error){
return $error->getMessage();
}
}
and y let my curl config
public static function curlClientInit(){
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, self::getWsdl());
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, self::getContext());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, self::getRequest());
$response = curl_exec($ch);
return $response;
}catch(\Exception $error) {
if (empty($response)) {
throw new SoapFault('CURL error: '.curl_error($ch), curl_errno($ch));
}
}
curl_close($ch);
}
so my result if i test this return to me a 0 and i expect this error
{
"error": "Credenciales no vĂ¡lidas"
}
and if past an asociative array instance a json and i use json_enconde so return false and i dont now why cause if do the same in postman i give the error cuse i expected
It is correct to use json_encode instead of putting in an array for the CURL_POSTFIELDS if you are accessing a JSON api.
The built-in json_encode function often fails to encode a data, if you did not set the proper $options flag for the data. This is quite annoying actually.
When it returns false, you can call json_last_error_msg() to learn the reason why it cannot encode your data. That would hopefully let us dig more into the problem.
For some reason when I moved my source code to google app engine,
curl start to return error number 3:
CURLE_URL_MALFORMAT (3) - The URL was not properly formatted.
important to say that the request got properly and still return error numer 3.
Any ideas?
Attach curl call:
<?php
function fire($url) {
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$content = curl_exec($ch);
$err_code = curl_errno($ch);
if ($err_code) {
return $err_code;
} else {
return $content;
}
} catch (Exception $e) {
return false;
}
}
?>
I am new to elastic search. I have one URL. Directly when executing that URL, I am getting results. But when I am trying to run this using curl, I am not getting any data. Below is my link
http://localhost:9200/bank/_search?q=address:mill
and the sample response from above link I am getting is
{"took":1,"timed_out":false,"_shards": {"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":4.8004513,"hits":[{"_index":"bank","_type":"account","_id":"136","_score":4.8004513,"_source":{"account_number":136,"balance":45801,"firstname":"Winnie","lastname":"Holland","age":38,"gender":"M","address":"198 Mill Lane","employer":"Neteria","email":"winnieholland#neteria.com","city":"Urie","state":"IL"}
}]}}
below is the curl program for above url.
$url = "localhost:9200/bank/account/_search?q=mill";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
var_dump($data);
You need to use HTTPGET option of CURLOPT and then You need to append your parameters with the url.
Try below code :
<?php
try {
$url = "http://localhost:9200/bank/_search";
$search_val = 'mill';
$str = "q=address:".$search_val;
$url_final = $url.'?'.$str;
$ch = curl_init();
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_URL, $url_final);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
if (FALSE === $return)
throw new Exception(curl_error($ch), curl_errno($ch));
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
curl_close ($ch);
echo $return;
?>
I am trying to post data using cURL to my web services to store data into database there, but it's storing the same data two times, instead of one. I applied condition there and it's working but i can not find the reason behind that behavior.
$postedArray['login_credentials'] = $this->login_data;
$postedArray['post_data'] = $this->arrPostData;
$str = http_build_query($postedArray);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_URL, $this->requestUrl);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 999);
curl_setopt($ch, CURLOPT_TIMEOUT, 999);
if (curl_exec($ch) === false) {
echo 'Curl error: ' . curl_error($ch);
return false;
}
$response = curl_exec($ch);
$response = json_decode($response, true);
curl_close($ch);
return $response;
Because you are actually calling curl_exec 2 times:
if (curl_exec($ch) === false) {
echo 'Curl error: ' . curl_error($ch);
return false;
}
$response = curl_exec($ch);
The first time while evaluating the response inside the if, and then again after the if. One should be dropped.
use curl_exec($ch) only once, code should look like this:
// code goes here
$response = curl_exec($ch);
if ($response === false)
{
echo 'Curl error: ' . curl_error($ch);
return false;
}
else
{
$json_response = json_decode($response, true);
}
curl_close($ch);
return $json_response;