How to execute curl within php loop? - php

I have used postman to execute curl request and get response from the api. Everything is working perfectly. But as soon as I try to execute same curl within a php while loop. It doesn't works at all.
Searched over the internet but did not found any useful information. I would like to know if there is any other way, other than using curl. I also tried sleep(3) function from php which sleeps loop for 3 seconds but it didn't helped.
Bottom line curl is not working in php loop whereas it works independently.
Below is my code for reference
while (($company = fgets($handle)) !== false) {
// process the line read.
$company = trim($company);
if(!empty($company)) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.domain.com/services/v3/api/entities?search-term=$company&page-size=10000",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer 78654356gvgfdr43wsdxcfg",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response_array = json_decode($response, TRUE);
$items = $response_array['items'];
if (!empty($items)) {
foreach ($items AS $item) {
$tt_id = $item['tt_id'];
$tt_Name = $item['tt_Name'];
$tt_TypeID = $item['tt_TypeID']['id'];
//save to db
}
}
}
}
I tried putting curl init and other setopt before the while loop, but it is not working either.
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_POSTFIELDS, "");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer 78654356gvgfdr43wsdxcfg",
"cache-control: no-cache"
));
while (($company = fgets($handle)) !== false) {
// process the line read.
$company = trim($company);
if(!empty($company)) {
curl_setopt($curl, CURLOPT_URL, https://api.domain.com/services/v3/api/entities?search-term=$company&page-size=10000);
$response = curl_exec($curl);
$err = curl_error($curl);
$response_array = json_decode($response, TRUE);
$items = $response_array['items'];
if (!empty($items)) {
foreach ($items AS $item) {
$tt_id = $item['tt_id'];
$tt_Name = $item['tt_Name'];
$tt_TypeID = $item['tt_TypeID']['id'];
//save to db
}
}
}
}
curl_close($curl);

Related

Openfigi php request -> Request body must be a JSON array

I am trying to use the openfigi api with php. I keep getting this error message: "Request body must be a JSON array.". Any ideas on how to solve this? I have tried several solutions.
$curlUrl = 'https://api.openfigi.com/v2/mapping';
$data = array('idType' => 'ID_WERTPAPIER', 'idValue' => '851399', 'exchCode' => 'US');
$j = json_encode($data);
//$apiToken = 'X-OPENFIGI-APIKEY: xxx';
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Content-Type: application/json';
//$httpHeadersArray[] = $apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $j);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);
$res = curl_exec($ch);
echo "<pre>";
print_r($res);
echo "</pre>";
had the same problem, but solved it.
This is my working code:
// The url you wish to send the POST request to
$url = 'https://api.openfigi.com/v2/mapping/';
// Create a new cURL resource
$ch = curl_init($url);
// The data to send to the API
$postData = array(
array(
"idType" => "ID_ISIN",
"idValue" => "US4592001014"
)
);
// Setup cURL
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => json_encode($postData)
));
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
print_r(json_encode($postData));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
print_r($responseData);

how to get data from mailchimp using php curl in laravel

I my Laravel app i am using php curl for mailchimp to store and get products data is storing but when i want to fetch data using foreach loop it is showing an error Trying to get property 'stores' of non-object how can i solve this thanks in advance
this is the result when i use dd()
this is the request
public function get_store()
{
$id = "store_1159";
$url = "https://us7.api.mailchimp.com/3.0/ecommerce/stores";
$data = callAPI('GET', $url, false);
$stores = json_decode($data);
//dd($stores );
$result = array();
foreach ($stores as $store) {
echo $store->id;
}
}
this is php curl main function
function callAPI($method, $url, $data=null)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
default:
if($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
$headers = array(
"--user: credentials",
"Authorization: Basic 1232132131",
"Content-Type: application/json",
"Postman-Token: 163f7134-68ca-45bb-9420-ebf2bef7f447",
"cache-control: no-cache"
);
curl_setopt_array($curl,
[
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADER => false,
CURLOPT_URL => $url.'?apikey=12313123'
]);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
try this,
$data = callAPI('GET', $url, false);
$data = json_decode($data);
foreach ($data->stores as $store)
{
echo $store->id;
}

Upload file using Curl and receive them in Laravel method

I have been trying to upload file to using curl using laravel app end point.
Below code is on separate server.
$header = $this->getCurlHeader();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$cfile = new \CURLFile($this->filePath . $this->csvFile, 'text/csv','text.csv');
//print_r($cfile);exit;
$postData = array('csv' => $cfile);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$response = curl_exec($ch);
$hhtpCode = curl_getinfo($ch);
curl_close($ch);
//$this->dbg($hhtpCode);
$this->dbg(json_decode($response,1),1);
And receiving end in laravel app hosted on different server.
public function insert(Request $request, $feed=''){
//return response()->json(var_dump($request->all()));
//return response()->json("here in insert");
return response()->json($_FILES);
echo "here";
dd($_FILES);
}
It returns me empty response.
I am able to verify curl request using headers.
Any suggestion will be helpful.
Thanks.
You can try something like this on the source server instead:
$target_url = 'https://mywebsite.com'; // Write your URL here
$dir = '/var/www/html/storage/test.zip'; // full directory of the file
$cFile = curl_file_create($dir);
$post = array('file'=> $cFile); // Parameter to be sent
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=json_decode(curl_exec($ch));
curl_close ($ch);
From the destination server, print the request sent.
public function insert(Request $request){
dd($request->file);
}
please use curlfile method to upload files.
if(isset($_FILES) && !empty($_FILES['identity_doc']))
{
foreach($_FILES['identity_doc'] as $key => $file)
{
$data['document'.$i]= new CURLFile($_FILES['identity_doc']['tmp_name'][$i], $_FILES['identity_doc']['type'][$i],$_FILES['identity_doc']['name'][$i]);
}
}
if(isset($_POST['submit']))
{
$fileName=$_FILES['resume']['name'];
$type=$_FILES['resume']['type'];
$tempPathname=$_FILES['resume']['tmp_name'];
$handle = fopen($tempPathname, "r");
$POST_DATA = fread($handle, filesize($tempPathname));
$url="https://objectstorage.region-name.oraclecloud.com/p/par-id/n/namespace`enter code here`/b/bucket-name/o/images/".$fileName;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS=>$POST_DATA ,
CURLOPT_HTTPHEADER => array(
'Content-Type: '.$type,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($response) {
echo 'error';
} else {
echo $url;
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="resume">
<button type="submit" name="submit">submit</button>
</form>

How to add contact in list using (Send Grid) php api

I am trying to add contact in list using php api but its throwing bellow snippet error
string(51) "{"errors":[{"message":"request body is invalid"}]} " {"email":"hello#test.com","first_name":"hh","last_name":"User"}
I am using bellow snippet code:
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists/12345/recipients'; //12345 is list_id
$params = array(
'email' => 'hello#test.com',
'first_name' => 'hh',
'last_name' => 'User'
);
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.XXXXXXXX");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
echo $json_post_fields;
Can any one tell me how to resolve this issue.
You should inspect the request that you are sending and compare the JSON in the body to a valid request to really see what's happening. The output of your json_encode here will be an array, but the API expects an object. Your request body needs to be
[{"email":"hello#test.com","first_name":"hh","last_name":"User"}]
And what you are doing right now is sending
{"email":"hello#test.com","first_name":"hh","last_name":"User"}
You can fix this several ways. You could use your favorite string manipulation functions to append the brackets, or you could skip the encoding and send the JSON as a string (since you're specifying the content type).
After looking at sendgrid API and then testing on my own server I was able to add contacts to the contact list. As you already created a list next step is to create recipients to be added to the list. You can do this way
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/recipients'; //12345 is list_id
$params = array(array(
'email' => 'amitkray#gmail.com',
'first_name' => 'Amit',
'last_name' => 'Kumar'
));
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.000000");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
curl_close($ch);
}
var_dump($data);
?>
After creating recipients you can now add them to list. You will get an id like this YW1pdGtyYXlAZ21haWwuY29t which is base64 encode of your email id.
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/lists/12345/recipients/YW1pdGtyYXlAZ21haWwuY29t'; //12345 is list_id
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.00000000");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
curl_close($ch);
}
var_dump($data);
?>
After adding that you can verify if user has been added to list
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/lists/12345/recipients?page_size=100&page=1'; //12345 is list_id
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.000000");
curl_setopt($ch, CURLOPT_GET, true);
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
curl_close($ch);
}
var_dump($data);
?>
Note: best way is to create a class as most of the codes are being repeated. I will make a wrapper class for sendgrid and post it here soon with ability to do all task that is possible through sendgrid API.
First think is you will need to insert your email to send grid recipients:
<?php
$curl = curl_init();
$email = "example#mail.com";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/contactdb/recipients",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "[{\"email\": \".$email.\"}]",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer SG.0000000",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
$a = json_decode($response);
$b = $a->persisted_recipients; //get id of email
$r_id = $b[0]; // store it
}
?>
after that insert it in list by doing this way.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendgrid.com/v3/contactdb/lists/123456/recipients/$r_id",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "null",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer SG.0000000000",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
for more info visit:https://sendgrid.com/docs/API_Reference/api_v3.html

PHP cURL: how to set body to binary data?

I'm using an API that wants me to send a POST with the binary data from a file as the body of the request. How can I accomplish this using PHP cURL?
The command line equivalent of what I'm trying to achieve is:
curl --request POST --data-binary "#myimage.jpg" https://myapiurl
You can just set your body in CURLOPT_POSTFIELDS.
Example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Taken from here
Of course, set your own header type, and just do file_get_contents('/path/to/file') for body.
This can be done through CURLFile instance:
$uploadFilePath = __DIR__ . '/resource/file.txt';
if (!file_exists($uploadFilePath)) {
throw new Exception('File not found: ' . $uploadFilePath);
}
$uploadFileMimeType = mime_content_type($uploadFilePath);
$uploadFilePostKey = 'file';
$uploadFile = new CURLFile(
$uploadFilePath,
$uploadFileMimeType,
$uploadFilePostKey
);
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify array of form fields
*/
CURLOPT_POSTFIELDS => [
$uploadFilePostKey => $uploadFile,
],
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
See - https://github.com/andriichuk/php-curl-cookbook#upload-file
to set body to binary data and upload without multipart/form-data, the key is to cheat curl, first we tell him to PUT, then to POST:
<?php
$file_local_full = '/tmp/foobar.png';
$content_type = mime_content_type($file_local_full);
$headers = array(
"Content-Type: $content_type", // or whatever you want
);
$filesize = filesize($file_local_full);
$stream = fopen($file_local_full, 'r');
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PUT => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_INFILE => $stream,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
fclose($stream);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
credits: How to POST a large amount of data within PHP curl without memory overhead?
Try this:
$postfields = array(
'upload_file' => '#'.$tmpFile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'/instances');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
}
curl_close($ch);
Below solution worked fine for me.
$ch = curl_init();
$post_url = "https://api_url/"
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$post = array(
'file' => '#' .realpath('PATH_TO_DOWNLOADED_ZIP_FILE')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$headers[] = 'Authorization: Bearer YOUR_ACCESS_TOKEN';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
refered: curl to php-curl
You need to provide appropriate header to send a POST with the binary data.
$header = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_POSTFIELDS, $arr_containing_file);
Your $arr_containing_file can for example contain file as expected (I mean, you need to provide appropriate expected field by the API service).
$arr_containing_file = array('datafile' => '#inputfile.ext');

Categories