Duplicate data stored when using cURL - php

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;

Related

Pipedrive - Updating a Lead Returns 404 not found

I am trying to update a LEAD using this URL
$lead_url = ‘https://’.$company_domain.’.pipedrive.com/api/v1/leads/’ . $leadID . ‘?api_token=’ . $PD_API_KEY;
But it returns 404 Not Found. When I check this URL in the browser it returns the complete information of that lead.
Here is my Curl Code:
function pipedrive_update_curl($arr , $endpoint)
{
$response = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($arr));
//***//
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//**//
$response_result = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors = curl_error($ch);
curl_close($ch);
$response['error'] = $curl_errors;
$response['status'] = $status_code;
$response['response'] = $response_result;
return $response;
}
Can somebody please explain where I am going wrong?
PUT method for updating leads is not supported.
see docs and pipedrive community posts:
https://developers.pipedrive.com/docs/api/v1/Leads#updateLead
https://devcommunity.pipedrive.com/t/put-not-working-when-updating-a-lead/3629

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.

displaying curl results using php

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;
?>

var_dump of a JSON response returns NULL

I'm writing a script to accept Bitcoin payments. My $json variable returns null. var_dump() returns NULL.
Things I've tried: 1. I've taken the value of $callbackurl and $recievingaddress pasted a URL directly into my browser and I have gotten a JSON response
I've used json_last_error and recieved a 'no error' response
I've escaped magic_quotes but this has no effect
What am I doing wrong?
$receiving_address = BITCOIN_ADDRESS;
if(get_magic_quotes_gpc()){
$callback_url = urlencode(stripslashes(CALLBACK_URL));
} else {
$callback_url = urlencode(CALLBACK_URL);
}
$ch = curl_init("https://blockchain.info/api/receive?method=create&address=$receiving_address&shared=false&callback=$callback_url");
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json=json_decode(curl_exec($ch),true);
var_dump($json);
echo $json[0]->text;
Corrected code is as follows:
$receiving_address = BITCOIN_ADDRESS;
if (get_magic_quotes_gpc()) {
$callback_url = urlencode(stripslashes(CALLBACK_URL));
} else {
$callback_url = urlencode(CALLBACK_URL);
}
$ch = curl_init("https://blockchain.info/api/receive?method=create&address=$receiving_address&shared=false&callback=$callback_url");
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CAINFO, "C:\Program Files\BitNami WAMPStack\apache2\htdocs\coming\cacert.pem");
$res = curl_exec($ch);
if ($res === FALSE) {
die("Curl failed with error: " . curl_error($ch));
}
//var_dump($res);
$json = json_decode($res, true);
Do NOT chain your curl/json calls like that. You're simply assuming we live in a perfect world and nothing could ever fail. That is a very bad decision. Always assume that external resources can and will fail, and check for failure at each stage. Change your code to:
$response = curl_exec($ch);
if ($result === FALSE) {
die("Curl failed with error: " . curl_error($ch));
}
$json = json_decode($response, true);
if (is_null($json)) {
die("Json decoding failed with error: ". json_last_error());
}

PHP Curl How to extract header's

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://test.com");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'x=32423');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
'OK';
}
This is what outputted,when i run this page
access_token=AAAdsfsdfds32432fadfcazdfadsfadsfdas
How do i extract this and pass it a variable?
There is a typo in your postfields. The postfields should be as follows:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('x'=>'32423'));
instead of:
curl_setopt($ch, CURLOPT_POSTFIELDS, 'x=32423'');
First off, you need to change your CURLOPT_HEADERS to true, and you need
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
and
$result=curl_exec($ch)
if( $result=== false)
Then, according to an answer I saw elsewhere on SO, this should get you the headers:
list($headers,$content) = explode("\r\n\r\n",$result,2);
foreach (explode("\r\n",$headers) as $hdr)
print_r($hdr); //see what it gives you and then edit this accordingly.
echo $content;
Sounds like you just want
$token = end(explode('=', $access_token_string));

Categories