Example:
curl H "Contenttype: application/xml" \
H "AcceptCharset: utf8" \
H "openapikey:50667854bb253d281ce0fe36ebaeebaa" \
api.11street.com.my
How to I authenticate in PHP using curl by using the information above?
After that I want to add product by using curl. Below is my code and it is not working. Website URL: http://lazino.com.my/super/marketplace/11street.php
Reference:
<?php
$ch = curl_init();
//COOKIES
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
// Headers
$headers = array();
$headers[] = 'Content-Type: application/xml; charset=utf-8';
$headers[] = 'openapikey:50667854bb253d281ce0fe36ebaeebaa';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// URL
curl_setopt($ch, CURLOPT_URL, 'http://api.11street.my/rest/prodservices/product');
$fields_string = array(
'selMthdCd' => "01",
'dispCtgrNo' => "1",
'prdTypCd' => "01",
'prdNm' => "TEST product",
'prdStatCd' => "01",
'prdWght' => "0.1",
'minorSelCnYn' => "Y",
'prdImage01' => "http://staticfs.nexgan.com/images/logo/sallyfashion.com.my_new.jpg",
'selTermUseYn' => "N",
'selPrc' => "25.00",
'prdSelQty' => "0",
'asDetail' => "test",
'dlvMthCd' => "01",
'dlvCstInstBasiCd' => "11",
'rtngExchDetail' => "Test",
'suplDtyfrPrdClfCd' => "01"
);
curl_setopt($ch,CURLOPT_POST, sizeof($fields_string));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$html = curl_exec($ch);
curl_close($ch);
echo $html;
?>
The -H directives are just headers, so you can set them as is described by this SO: PHP cURL custom headers, and then make your GET request using curl_exec. If you're not familiar with HTTP verbs I'd suggest reading this: http://www.restapitutorial.com/lessons/httpmethods.html
To authenticate with cURL from PHP:
<?php
$ch = curl_init();
//COOKIES
curl_setopt($ch, CURLOPT_COOKIEFILE, 'path/to/cookies.txt');
// Headers
$headers = array();
$headers[] = 'Content-Type: application/xml; charset=utf-8';
$headers[] = 'openapikey:50667854bb253d281ce0fe36ebaeebaa';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// URL
curl_setopt($ch, CURLOPT_URL, 'api.11street.com.my');
$html = curl_exec($ch);
curl_close($ch);
I think you can find more answers if you just search a little on this website..
UPDATE:
Maybe something like this ?
<?php
$ch = curl_init();
//COOKIES
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
// Headers
$headers = array();
$headers[] = 'Content-Type: application/xml';
$headers[] = 'openapikey:50667854bb253d281ce0fe36ebaeebaa';
// URL
curl_setopt($ch, CURLOPT_URL, 'http://api.11street.my/rest/prodservices/product');
$xml = "<xml>
<selMthdCd>01</selMthdCd>
<dispCtgrNo>1</dispCtgrNo>
<prdTypCd>01</prdTypCd>
<prdNm>TEST PRODUCT</prdNm>
<prdStatCd>01</prdStatCd>
<prdWght>0.1</prdWght>
<minorSelCnYn>Y</minorSelCnYn>
<prdImage01>http://staticfs.nexgan.com/images/logo/sallyfashion.com.my_new.jpg</prdImage01>
<selTermUseYn>N</selTermUseYn>
<selPrc>25.00</selPrc>
<prdSelQty>0</prdSelQty>
<asDetail>test</asDetail>
<dlvMthCd>01</dlvMthCd>
<dlvCstInstBasiCd>11</dlvCstInstBasiCd>
<rtngExchDetail>Test</rtngExchDetail>
<suplDtyfrPrdClfCd>01</suplDtyfrPrdClfCd>
</xml>";
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $xml );
$html = curl_exec($ch);
curl_close($ch);
echo $html;
What is the server supposed to recieve ?
Related
I've tried changing things around and all I every get is 'false'.
(I was getting errors until I fixed a problem with the strlen) - now just false.
(I have no problem getting records to view)
I have tried this as PUT and PATCH...
$user = 'someuser';
$base_url = 'https://creator.zoho.com';
$url = "$base_url/api/v2/$user/client-list-2/report/Contact";
$ch = curl_init($url);
$criteria = "ID=98989231239213"; // id is not a string in zoho
$fields = json_encode(
[ "criteria" => $criteria,
"data" => ["RBT_ID" => "$rbt_id"] / RBT_ID is a string in zoho
]
);
$fields_length = strlen($fields);
$header = array('Content-Type: application/json',
"Content-Length: $fields_length",
"Authorization: Zoho-oauthtoken $creds->access_token");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = curl_exec($ch);
curl_close($ch);
I am trying to upload a video using LinkedIn API V2 but I am unable to post successfully video to my LinkedIn Individual Account.
Please help.
Returning Below Response from LinkedIn API:
SignatureDoesNotMatch
The request signature we calculated does not match the signature you provided. Check your key and signing method.
$person_id=LINKEDIN_ACCOUNT_ID;
$access_token= LINKEDIN_ACCESS_TOKEN;
$share_text='Video Upload and Share Text';
$author = "urn:li:person:".$person_id;
$r_url='https://api.linkedin.com/v2/assets?action=registerUpload';
$r_params = array(
'registerUploadRequest'=>array(
'recipes'=>array('urn:li:digitalmediaRecipe:feedshare-video'),
'owner' => $author,
)
);
$handle = curl_init();
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_URL, $r_url);
curl_setopt($handle, CURLOPT_VERBOSE, FALSE);
$header = array();
$header[] ='Authorization : Bearer '.$access_token;
$header[] = 'Content-Type: application/json; charset=UTF-8';
curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($r_params));
$json1 = curl_exec($handle);
$json1=json_decode($json1,true);
if($json1['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl']){
$target_url=$json1['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'];
$return_header=$json1['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['headers'];
$parts = parse_url($target_url);
parse_str($parts['query'], $query);
$amz_signature=$query['X-Amz-Signature'];
$target_header=array();
$target_header[]='Host: video-uploads-prod.s3-accelerate.amazonaws.com';
$target_header[]="Content-Type:".trim($return_header['Content-Type']);
$target_header[]="x-amz-server-side-encryption:".trim($return_header['x-amz-server-side-encryption']);
$target_header[]='x-amz-server-side-encryption-aws-kms-key-id:'.trim($return_header['x-amz-server-side-encryption-aws-kms-key-id']);
$video_path = DIR_PATH_TO_VIDEO_FILE.'example_video.mp4';
$post_data=array('file'=>$video_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $target_header);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($video_path));
$json2=curl_exec ($ch);
curl_close ($ch);
$json2=json_decode($json2,true);
$media_id=str_replace('urn:li:digitalmediaAsset:','', $json1['value']['asset']);
$return_data=array();
$check_url = 'https://api.linkedin.com/v2/assets/'.$media_id;
$handle = curl_init();
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($handle, CURLOPT_HEADER, FALSE);
curl_setopt($handle, CURLOPT_URL, $check_url);
$header = array();
$header[] ='Authorization : Bearer '.$access_token;
$header[] = 'Content-Type: application/json; charset=UTF-8';
curl_setopt($handle, CURLOPT_HTTPHEADER,$header);
$return_data= curl_exec($handle);
$return_data= json_decode($return_data,true);
$author = "urn:li:person:".$person_id;
$post_url = 'https://api.linkedin.com/v2/ugcPosts';
$media_data=array();
$media_data[0]=array(
'status'=>'READY',
'description'=>array('text'=>'Official LinkedIn Blog'),
'media'=>$media_id,
'title'=>array('text'=>"Official LinkedIn Blog"),
);
$params = array(
'author' => $author,
'lifecycleState' => 'PUBLISHED',
'specificContent' => array(
'com.linkedin.ugc.ShareContent' => array(
'shareCommentary' => array(
'text' => "Video media set in post",
),
'shareMediaCategory' => 'VIDEO',
'media'=>$media_data,
'originalUrl'=>'https://www.google.com'
)
),
'visibility' => array(
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC'
)
);
$handle = curl_init();
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_URL, $post_url);
curl_setopt($handle, CURLOPT_VERBOSE, FALSE);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($params));
$header = array();
$header[] ='Authorization : Bearer '.$access_token;
$header[] = 'Content-Type: application/json; charset=UTF-8';
$header[] = 'X-Restli-Protocol-Version:2.0.0';
curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
$json3 = curl_exec($handle);
$json3=json_decode($json3);
I need to upload video post to LinkedIn Account successfully but I am unable to understand that from LinkedIn documentation too. I have tried so much but not succeed.
Please someone who has successfully uploaded a video with V2 then please help.
Hi linkedin not released video uploads yet.You can use the article EP( "shareMediaCategory": "ARTICLE") to send videos to linkedin
I make use of the LinkedIn API from Zoonman to do the client post request, but this is out of the scope of the question.
Because i could not get the php curl functions to work properly, i am using the command line interface to do the request, and it works! See my code below.
BUT. even tough the upload works. When i do a request to get the status of the upload, it is still "WAITING_UPLOAD". So i think #augustine jenin is right, that it is not supported yet. (may 2019)
<?php
// first register upload
$data = [
"registerUploadRequest" => [
"recipes" => [
"urn:li:digitalmediaRecipe:feedshare-video"
],
"owner" => "urn:li:organization:" . $liPageId,
"serviceRelationships"=> [
[
"relationshipType"=> "OWNER",
"identifier" => "urn:li:userGeneratedContent"
]
]
]
];
$register = $client->post('assets?action=registerUpload', $data);
// get upload url and header
$uploadUrl = $register["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"];
$headers = $register["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["headers"];
$curlHeaders = "";
foreach($headers as $htype => $header) {
$curlHeaders .= ' -H "' . $htype . ':' . $header . '"';
}
// go upload the image to the url
$filePath = "/path/to/your/file";
$command = '/usr/bin/curl -v';
$command .= $curlHeaders;
$command .= ' --upload-file \'' . $filePath . '\' \'' . $uploadUrl . '\'';
// try it yourself by running this on the command line
//echo $command;
shell_exec($command);
?>
I'm working on how do I export a dashboard from some specific project, like this link shows up.
The code I made, generates the link for download correctly, like expected. But the PDF file exported don't bring the values filtered like I aimed.
My problem happen below this comment:
// Execute the dashboard with context
... where I supose to set "all filters that affects the dashboard", like the link above says. But it does not specify how can I set the value of the filter.
I made all the code in PHP (replace all the "{some-thing}" to make this code work):
<?php
$login = '{email}';
$pass = '{password}';
$headers = array('accept' => 'Accept: application/json','content-type' => 'Content-Type: application/json; charset=utf-8');
$data = json_encode(array('postUserLogin'=>array('login'=> $login,'password'=> $pass,'remember'=>0)));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://secure.gooddata.com/gdc/account/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
$AuthSST = substr($output, strrpos($output, "GDCAuthSST=")+strlen("GDCAuthSST="), 17);
$headers = array('accept' => 'Accept: application/json',
'content-type' => 'Content-Type: application/json; charset=utf-8',
'cookie:' => 'Cookie: $Version=0; GDCAuthSST='.$AuthSST.' $Path=/gdc/account');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_URL, "https://secure.gooddata.com/gdc/account/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
$start = strrpos($output, "GDCAuthTT=")+strlen("GDCAuthTT=");
$finish = strrpos($output, "Path=/gdc");
$GDCAuthTT = substr($output, $start, ($finish-$start));
$headers = array('accept' => 'Accept: application/json',
'content-type' => 'Content-Type: application/json; charset=utf-8',
'cookie:' => 'Cookie: $Version=0; GDCAuthTT='.$GDCAuthTT.' $Path=/gdc/account');
// Authentication finished, now start the dashboard export API
// Execute the dashboard with context
$project_id = '{project_id}';
$filter_id = '{filter_id}';
$filter_obj = '{0000}';
$dash_obj = '{0000}';
$url = 'https://secure.gooddata.com/gdc/internal/projects/'.$project_id.'/executionContexts';
// Inside filters: constraint, promptUri, uri, id ||||||||| Inside executionContext: dashboard, links, name, type, user
$bode = json_encode(array('executionContext' => array('filters' => array(array(
'uri' => '/gdc/md/'.$project_id.'/obj/'.$filter_obj, // /elements?id=0000
'id' => $filter_id)),
'dashboard' => '/gdc/md/'.$project_id.'/obj/'.$dash_obj,
'type' => 'export'
)));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bode);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
// Export the Dashboard
$dash_tab = 'ae2b1ab3a87c';
$start = strrpos($output, "\"uri\":\"")+7;
$finish = strrpos($output, "\"}");
$url = "https://secure.gooddata.com/gdc/projects/".$project_id."/clientexport";
$request_url = "https://secure.gooddata.com/dashboard.html#";
$project = "project=/gdc/projects/".$project_id;
$dashboard = "&dashboard=/gdc/md/".$project_id."/obj/".$dash_obj;
$tab = "&tab=".$dash_tab."&export=1";
$ctx = "&ctx=".substr($output, $start, ($finish-$start));
$bode2 = json_encode(array('clientExport'=>array('url'=>$request_url.$project.$dashboard.$tab.$ctx, 'name'=>'{Dash_Name}')));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bode2);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
// Poll the URL from response Result:
$start = strrpos($output, "\"poll\":\"")+8;
$finish = strrpos($output, "\"}");
$poll = "https://secure.gooddata.com".substr($output, $start, ($finish-$start));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_URL, $poll);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
echo "Link: ".$poll;
echo "<br>Output: ".$output;
// Wait 90 seconds and then make the download, otherwise it returns 202 http code
sleep(90);
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Accept: application/json\r\n".
"Content-Type: application/json; charset=utf-8\r\n".
'Cookie: $Version=0; GDCAuthTT='.$GDCAuthTT.' $Path=/gdc/account'."\r\n",
'timeout' => 6000
)
);
$context = stream_context_create($opts);
$file = file_get_contents($poll."?download=true", false, $context);
file_put_contents("Dashboard.pdf", $file);
echo "<br><br>Link used: ".$poll."?download=true";
$errors= error_get_last();
echo "<br><br>".$errors['type'];
echo "<br>".$errors['message'];
curl_close($ch);
?>
You can specify the filter values using constraint object in the filter definition. The exact constraint format depends on the type of the filter. If the filter is type of list the constraint format is:
"constraint": {
"type": "list",
"elements": [
"/gdc/md/{project_id}/obj/{attribute_id}?id={element_id}",
...
]
}
if it is a date filter the constraint looks like:
"constraint": {
"from": "2006-07-01",
"to": "2008-03-31",
"type": "interval"
}
or
"constraint": {
"from": -5,
"to": 0,
"type": "floating"
}
Example of the whole executionContext object for POST with one list filter with 2 values selected:
{
"executionContext": {
"filters": [
{
"uri": "/gdc/md/{project_id}/obj/{attribute_id}",
"constraint": {
"type": "list",
"elements": [
"/gdc/md/{project_id}/obj/{displayForm_id}/elements?id={element_id_1}",
"/gdc/md/{project_id}/obj/{displayForm_id}/elements?id={element_id_2}"
]
},
"id": "{filter_id}"
}
],
"dashboard": "/gdc/md/{project_id}/obj/{dashboard_id}",
"type": "export"
}
}
You can see the valid example of filter constraint e.g. in the docs for handling drills or creating of saved view.
Hi I have managed to successfully generate a FPDF pdf file from my form submission. I have then POSTED it via CURL to an API endpoint.
This 'file' shows inside the CRM system where supposed go but I cannot open it.
I believe this is not the file at all and it is not being passed stored/grabbed properly.
Thanks
See below code:
$noteTitle = (isset($_POST['noteTitle']) ? $_POST['noteTitle'] : null);
$noteBody = (isset($_POST['noteBody']) ? $_POST['noteBody'] : null);
require("fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont("Arial", "B", 16);
$pdf->Cell(0,100, "Note Title: {$noteTitle} \n", 1, 0, 'C');
$pdf->Cell(0,100, "Note Body: {$noteBody}", 1, 0, 'C');
$filename="testFPDF.pdf";
$pdf->Output($filename,'F');
$headers2 = array(
"authorization: Basic xxx",
"content-type: multipart/form-data",
"cache-control: no-cache",
"postman-token: xxx"
);
$file_name_with_full_path = 'C:/localhost/insightly-php/testFPDF.pdf';
$timeout = 30;
$target_url = "https://api.insight.ly/v2.1/Notes/?c_id=" . $noteID . "&filename=" . $filename;
$parameters = array(
'FILE_ATTACHMENTS' => '#' . $file_name_with_full_path,
'CONTENT_TYPE' => 'application/pdf'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_ENCODING,"");
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
//curl_setopt($ch, CURLOPT_MAXREDIRS,10);
//curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
//curl_setopt( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_exec($ch);
curl_close ($ch);
File contents are:
--------------------------xxxxxxxxxxxxxxxx
Content-Disposition: form-data; name="FILE_ATTACHMENTS"
#C:/localhost/insightly-php/testFPDF.pdf
--------------------------xxxxxxxxxxxxxxxx--
Hi I managed to get this working. I am not sure if this is the best way of doing it but it worked.
It was to convert the output of the fpdf as a string $doc = $pdf->Output($filename,'S'); then decode it before sending the curl var_dump(json_decode($doc, true)); & also make the header content type "application/pdf"
$noteTitle = (isset($_POST['noteTitle']) ? $_POST['noteTitle'] : null);
$noteBody = (isset($_POST['noteBody']) ? $_POST['noteBody'] : null);
//FPDF
require("fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont("Arial", "B", 14);
$pdf->Cell(0,50, "Note Title: {$noteTitle}", 1, 0, 'C');
$pdf->Cell(0,50, "Note Body: {$noteBody}", 1, 0, 'C');
$filename="testFPDF.pdf";
$doc = $pdf->Output($filename,'S');
///////////FIRST POST REQUEST////////////
$orgID = 70239678;
$addNote = (object)array(
"TITLE" => "$noteTitle",
"BODY" => "$noteBody ",
"LINK_SUBJECT_ID" => "$orgID",
"LINK_SUBJECT_TYPE" => "Organisation"
);
$addNote = $i->addNote($addNote);
///////////GET NOTE ID////////////
$orgNotes = $i->getNotes(array("orderby" => 'DATE_CREATED_UTC'));
foreach ($orgNotes as $note) {
$noteID = $note->NOTE_ID;
}
///////////SEND ATTACHEMENT////////////
$headers2 = array(
"authorization: Basic xxx",
"content-type: application/pdf",
"cache-control: no-cache",
"postman-token: xxx"
);
$target_url = "https://api.insight.ly/v2.1/Notes/?c_id=" . $noteID . "&filename=" . $filename;
var_dump(json_decode($doc, true));
$parameters = array(
'FILE_ATTACHMENT' => $doc
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
curl_close ($ch);
If anyone is interested this is my solution for using file upload instead of the fpdf send solution. Multipart form file upload POST PHP cURL
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');