Uploading a file (server to server) with PHP using cURL - php

I have the following php code from my API console on RapidApi working correctly:
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://webit-computer-vision.p.rapidapi.com/describe",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => 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=\"image\"\r\n\r\n\r\n-----011000010111000001101001--\r\n\r\n",
CURLOPT_HTTPHEADER => [
"content-type: multipart/form-data; boundary=---011000010111000001101001",
"x-rapidapi-host: webit-computer-vision.p.rapidapi.com",
"x-rapidapi-key: XXXXXXXXXX"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The only problem is that it also includes a file which is sent to the endpoint. How can I upload file to the given endpoint? The content-type appears to already be set correctly. I believe I just need to send the content of file in addition.

for anyone wondering, I was able to get it working by modifying the header with this code:
CURLOPT_HTTPHEADER => [
"content-type: multipart/form-data",
"x-rapidapi-host: webit-computer-vision.p.rapidapi.com",
"x-rapidapi-key: VMssAjUwitmshMGT0yv1SbvOhkLVp1f3BaqjsnpKZ8t9yLcbxs"
]
and then had to change the following to get the image file to POST properly:
$fields = [
'image' => new \CurlFile("images/2021_04_01_Ied8W_Ex0P-meVoActjCQ.jpg", 'image/jpeg', 'filename.jpg')
];
...
CURLOPT_POSTFIELDS => $fields,
...
started working pretty quickly after that =)

Related

Microsoft Translator Text API CUrl PHP

I have to translate some information of my database to make PDF. I make a PHP function called "translate" that receive the strinf to be trtanslated by parameter. I have this API cURL code:
function translate($text)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://microsoft-translator-text.p.rapidapi.com/translate?to=fr&api-version=3.0&from=pt&profanityAction=NoAction&textType=plain",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "[\r
{\r
\"Text\": \"I would really like to drive your car around the block a few times.\"\r
}\r
]",
CURLOPT_HTTPHEADER => [
"X-RapidAPI-Host: microsoft-translator-text.p.rapidapi.com",
"X-RapidAPI-Key: KEY",
"content-type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$json = json_decode($response);
echo $json[0]->translations[0]->text;
}
}
I want to replace:
CURLOPT_POSTFIELDS => "[\r
{\r
\"Text\": \"I would really like to drive your car around the block a few times.\"\r
}\r
]",
with:
$text
But i donĀ“t know how. Can you help me?

How can I send whatsapp message to multiple numbers by using ultramsg and PHP

I am trying to send WhatsApp message to multiple numbers by using Ultramsg.com using PHP
by reference: https://docs.ultramsg.com/api/post/messages/chat
the code is like this:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.ultramsg.com/instance1xxx/messages/chat",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "token=exxxxxxxx&to=1408XXXXXX1 #c.us,1408XXXXXX2 #c.us&body=WhatsApp API on UltraMsg.com works good&priority=10",
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
but I am getting this error
"to": "Wrong 'to' format for element (1408xxxxxxx #c.us,1408xxxxxxx #c.us). 'to' format : 14155552671#c.us or 14155552671-441234567890#g.us"
I am not understanding this.
I think should try to remove space before #c.us

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'

Acumatica REST Contract-Based API and PHP Curl As ERROR Has Occured to Create Data

I've been trying to create customer in Acumatica contract-based REST API following TIM RODMAN method and a little tweak of code
and all I'm getting is an error
{"message":"An error has occurred."}
I have tried to get data (GET all data) has been successful, but when I try to create new data customer, purchase order or else i got an error appears as above
Note: The same create in Postman didn't work, but start from login, get data, and logout work fine.
See the code below for my latest version of simplified code
function login_acumatica($cookie_jar, $curl){
// Login to Acumatica REST API
curl_setopt_array($curl, array(
CURLOPT_URL => "http://111.11.111.11/AcumaticaMMI/entity/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_COOKIESESSION => 1,
CURLOPT_COOKIEJAR => $cookie_jar,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n \"name\": \"admin\",\r\n \"password\": \"1112345\",\r\n \"company\": \"DUMMY USER\"\r\n}",
CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "content-type: application/json"),
));
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
function logout_acumatica($cookie_jar, $curl){
// Logout of Acumatica REST API
curl_setopt_array($curl, array(
CURLOPT_URL => "http://111.11.111.11/AcumaticaMMI/entity/auth/logout",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_COOKIESESSION => 1,
CURLOPT_COOKIEFILE => $cookie_jar,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "content-type: application/json"),
));
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
// Close Connection
curl_close($curl);
// Remove Cookie Jar
unlink($cookie_jar) or die("Can't unlink $cookie_jar");
}
switch ($_GET['query']) {
case 'create_customer':
// Add Cookie Jar
$cookie_jar = tempnam('/tmp','cookie.txt');
// Initiate Connection
$curl = curl_init();
login_acumatica($cookie_jar, $curl);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://111.11.111.11/AcumaticaMMI/entity/Default/6.00.001/CUstomer",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{\n\t\"CustomerID\": {\"value\":\"C-00023\"},\n\t\"CustomerName\": {\"value\":\"Cust Test 1\"}\n}",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
logout_acumatica($cookie_jar, $curl);
break;
default:
echo dirname(__FILE__) . '/cookie.txt';
break;
}
sorry for my bad english. thanks in advance
Unless you're using OAuth (which you are not), Acumatica requires cookies for the authentication to work. Postman handles cookies autimatically. As far as I can see, you don't transfer cookies between login call and subsequent calls, which is why your setup doesn't work.
Try something like this from Tim Rodman
// Add Cookie Jar
$cookie_jar = tempnam('/tmp','cookie');
// Initiate Connection
$curl = curl_init();
// Login to Acumatica REST API
echo "START <br><br>";
curl_setopt_array($curl, array(
CURLOPT_URL => "http://111.11.111.11/AcumaticaIII/entity/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_COOKIESESSION => 1,
CURLOPT_COOKIEJAR => $cookie_jar,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n \"name\": \"admin\",\r\n \"password\": \"123\",\r\n }",
CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "content-type: application/json", "postman-token: e0a0ff40-8d46-4c5f-106b-960ad1aafba8"
),
));

How to consume my webservice with PHP

I have a question ..
My app gives me the following information:
HTTP + JSON
The following are sample HTTP requests and responses. The placeholders shown need to be replaced with actual values.
POST /json/reply/Zona
HTTP/1.1
Host: equatepro.azurewebsites.net
Content-Type: application/json
Content-Length: length
{"zonaId":0,"nombre":"String","creadoPor":"String","creadoFecha":"/Date(-62135596800000-0000)/","modificadoPor":"String","modificadoFecha":"/Date(-62135596800000-0000)/","estado":"String","nota":"String","borrar":false}
AND then
The following routes are available for this service:
POST /api/zonas
PUT /api/zonas/{zonaId}
enter image description here
enter image description here
I'm trying to communicate with my webservice using PUT method
My code
<?php
$pantalla="zonas";
%id =8;
$url= "http: //miapp.com /api/zonas/8".$pantalla ;
$url = $url ."/" . $id;
// complete url http://miapp.com/api/zonas/8
//build json
$ConstructorJson = array(
'ZonaId' => $Datos['txt_codigo'],
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
$json = json_encode($ConstructorJson);
$opts = array(
"http" => array(
"method" => "PUT",
"header" => "Accept: application/xml\r\n",
"content" => $json
)
);
$context = stream_context_create($opts);
$response = file_put_contents($url,'8',false,$context);
?>
Give me the following error
Warning: file_put_contents(http: //miapp .com/api/zonas/8): failed to open >stream: HTTP wrapper does not support writeable connections in C:\xampp\htdocs\Codigo2.0\models\zonas.model.php on line 34
and nothing happens.
I would rather connect using PHP curl.
$ConstructorJson = array(
'ZonaId' => $Datos['txt_codigo'],
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
$json = json_encode($ConstructorJson);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http: //miapp.com/api/zonas/8/zonas",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $json
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Accept: application/xml\r\n",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
HTTP wrapper does not support writeable connections - basically, PHP is telling you "Hey, you can't use this function to write to a file that lives on the internet. How do you expect me to write a file # http: //miapp .com/api/zonas/8? Not gonna happen".
I assume what you're trying to do is to send a PUT request # that location to update a zonas resource with ID 8.
Solution
Consider using a proper HTTP client that can send actual HTTP request methods and conform to the HTTP spec.
My personal favourite inside PHP is Guzzle -
http://docs.guzzlephp.org/en/stable/. Guzzle is a standalone package and can be downloaded from their site. You can use it in any PHP project - without or without a framework.
With Guzzle, you'd do something like the following:
$client = new GuzzleHttp\Client();
$json = json_encode($ConstructorJson);
$headers = [
"Accept" => "application/xml\r\n"
]
$request = new Request('PUT', $url, ['body' => $json, 'headers' => $headers]);
$client->send($request);
I finally solved the problem (thank you Kyle O'Brien)
Code
<?php
// web service url + tabla + id
$url = "mywebservice.com/zonas/8";
$Datos = $_POST;
//create a array with dates
$ConstructorJson = array(
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
//convert array to json
$json = json_encode($ConstructorJson);
$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 => $json,
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>

Categories