Downloading & Uploading a file with cURL - php

I have been trying to use cURL to interact with an api, I want to download a file with this snippet but all it does is open up the file in the browser and the second snippet is supposed to upload a pdf file along with multipart form data with cURL, but all it give me is;
"{"type":"request_error","detail":"Multipart form parse error - Invalid boundary in multipart: None"}"
error, I have already tried to execute the thing with postman, it runs fine there and when i copy and paste the same code it still gives me the same errors as above, cheers, thanks in advance.
Here is the code;
Downloading Snippet
$id = "rZFbMKmj2zZbMUbp5KrjCH";
$auth = $this->access_token;
$curl = curl_init( PANDA_APIURL . "/documents/".$id."/download");
//$fp = fopen('Test.pdf', 'w+');
curl_setopt_array($curl, array(
CURLOPT_URL => PANDA_APIURL . "/documents/".$id."/download",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 50,
CURLOPT_TIMEOUT => 300,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//CURLOPT_FILE => $fp,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $auth"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//fclose($fp);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Uploading the file with multipart form data snippet;
$auth = $this->access_token;
$boundary = '7aBMjcE3CIYntqQ3';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => PANDA_APIURL . "/documents",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '------WebKitFormBoundary7aBMjcE3CIYntqQ3
Content-Disposition: form-data; name="file"; filename="samplepdf.pdf"
Content-Type: application/pdf
------WebKitFormBoundary7aBMjcE3CIYntqQ3
Content-Disposition: form-data; name="data"
{
"name": "Pdf Doc",
"recipients": [
{
"email": "xyz#gmail.com",
"first_name": "Jane",
"last_name": "Roe"
}
],
"fields": {
"name": {
"value": "John"
},
"like": {
"value": true
}
}
}
------WebKitFormBoundary7aBMjcE3CIYntqQ3',
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $auth",
"Content-Type: multipart/form-data;----WebKitFormBoundary'.$boundary"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Related

bulk user import auth0 API

i am trying to import users to auth0 using "users import bulk api".
curl_setopt_array($curl, [
CURLOPT_URL => "https://***/api/v2/jobs/users-imports",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"filename.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\n********\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\n******\r\n-----011000010111000001101001--\r\n",
CURLOPT_HTTPHEADER => [
"authorization: Bearer ".$token."",
"content-type: multipart/form-data; boundary=---011000010111000001101001"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
i tried to get the file content with stream_get_contents and file_get_contents.
i always get the same error:
{“statusCode”:400," error":“Bad Request”, “message”:“Users file must not be empty.”, “errorCode”:“operation_not_supported”}

Determine the file type downloaded by cURL

I have this code,
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://example.com/v1/items/id/preview",
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 => [
"Accept: application/json",
"Authorization: Bearer bearer-string",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
file_put_contents('file.jpeg', print_r($response, true));
}
From that code I can tell that the response is jpeg that's why I assigned file.jpeg as filename.
Now my problem, what if the response is not jpeg?
I could not find any function from https://www.php.net/manual/en/ref.filesystem.php that will dynamically determine what type of file is in response.
Any Idea about this.
You can use curl_getinfo to get content-type of what curl got
$mime = curl_getinfo(response , CURLINFO_CONTENT_TYPE);
and then simply check if $mime equals to 'image/jpeg'

Error creating natural language classifier with api using PHP, returns data too small error but works in Postman

The cURL request works in Postman with the following:
curl -i -u "apikey:12345" \
-F training_data=#rtcu.csv \
-F training_metadata="{\"language\":\"en\",\"name\":\"RTCU\"}" \
"https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/v1/classifiers"
Postman's generated cURL code for PHP returns { "code" : 400, "error" : "Data too small", "description" : "The number of training entries received = 0, which is smaller than the required minimum of 5" }
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"training_data\"; filename=\"rtcu.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"training_metadata\"\r\n\r\n{\"language\":\"en\",\"name\":\"RTCU\"}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic 12345",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I've tried adding the "#" in front of the filename like suggested in other posts with no success. I haven't had this problem with other IBM Watson services and their cURL calls. What could be the issue?
Using CURLFile worked for me
$uploadFilePath = 'rtcu.csv';
$name = "RTCU";
$lang = "en";
$uploadFileMimeType = "text/csv";
$uploadFilePostKey = 'training_data';
$metaPostKey = "training_metadata";
$uploadFile = new CURLFile(
$uploadFilePath,
$uploadFileMimeType,
$uploadFilePostKey
);
$curlHandler = curl_init();
curl_setopt_array( $curlHandler, [
CURLOPT_URL => 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array(
"Authorization: Basic 12345",
"cache-control: no-cache"
),
CURLOPT_POSTFIELDS => [
$uploadFilePostKey => $uploadFile,
$metaPostKey => "{\"language\":\"{$lang}\",\"name\":\"{$name}\"}"
],
] );
$response = curl_exec( $curlHandler );
$err = curl_error( curlHandler );
curl_close( curlHandler );
if ( $err ) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}

Api request working with postman and resteasy but not working in php curl

This is the code generated by postman
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://smsgateway.me/api/v4/message/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "[\r\n {\r\n \"phone_number\": \"40404\",\r\n \"message\": \"whois #akborodo\",\r\n \"device_id\": 82531\r\n }\r\n \r\n ]",
CURLOPT_HTTPHEADER => array(
"authorization: <api-key>",
"cache-control: no-cache",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
when i try it it display HTTP ERROR 500 int the browser, but it practically worked well in postman

ALM SaaS REST API 12.50 not working in PHP

I have tried below code in PHP to get the defect details from ALM but its not showing any response in browser. But the same is working in POSTMAN . Can someone help me here
Here is the document of REST API USAGE REST DOCUMENT FROM ALM
I have already tried existing posts from Stackoverflow
HP ALM REST API login using PHP CURL
ALM REST API v12.50 error 401
Nothing is helping so posted a new question
Note : Due to security purpose header value is kept as encoded value
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://hostname/qcbin/api/domains/domainname/projects/projectname/defects/?limit=10",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic encoded value",
"cache-control: no-cache",
"postman-token: a8a2398d-7a0a-0ebd-a586-58a40e524a9a"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
I have finally found the solution and below is the approach
First we need get to LWSSO_COOKIE_KEY,QCSession,ALM_USER,XSRF_TOKEN values from the ALM Authentication link then we should use the values for subsequent calls
Below is the complete working code to get the list of defects by entering ALM Credentials
<?php
$curl = curl_init();
Header('Content-type: application/json');
$credentials = "username:password";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://host:port/qcbin/api/authentication/sign-in",
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($credentials) ,
"cache-control: no-cache"
) ,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
// If there is no error then get the response to form the array of headers to get the different values required
$array_start = explode(';', $response);
foreach ($array_start as $key => $value) {
$remove_from_string = ['HTTP/1.1 200 OK','Path=/','HTTPOnly','HttpOnly','Content-Length',': 0'];
$replace_array = ['','','','','',''];
$value = str_replace($remove_from_string,$replace_array,$value);
$value = trim(preg_replace(('/Expires: [a-zA-Z]+, [0-9]+ [a-zA-Z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ [a-zA-Z]+/'), '', $value));
$value = trim(preg_replace(('/Server: [a-zA-Z0-9.\(\)]+/'),'',$value));
if (!empty($value)) {
$almheaders[trim(explode('=',$value)[0])] = explode('=',$value)[1];
}
}
$LWSSO_COOKIE_KEY = $almheaders['Set-Cookie: LWSSO_COOKIE_KEY'];
$QCSession = $almheaders['Set-Cookie: QCSession'];
$ALM_USER = $almheaders['Set-Cookie: ALM_USER'];
$XSRF_TOKEN = $almheaders['Set-Cookie: XSRF-TOKEN'];
// Now form the Cookie value from the above values.
$cookie = "Cookie: JSESSIONID=33eyr1y736486zcnl0vtmo12;XSRF-TOKEN=$XSRF_TOKEN;QCSession=$QCSession;ALM_USER=$ALM_USER;LWSSO_COOKIE_KEY=$LWSSO_COOKIE_KEY";
// echo $cookie;
$curl = curl_init();
Header('Content-type: application/json');
curl_setopt_array($curl, array(
CURLOPT_URL => "https://host:port/qcbin/api/domains/CET_NTD/projects/BILLING_OPERATIONS/defects",
// CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($credentials) ,
"cache-control: no-cache",
"Accept: application/json",
$cookie
) ,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
echo $response;
}
}
?>

Categories