I am working on a project where I have to upload an image using cURL.
My image name is not getting saved properly in the Database.
I am sending below line of code to my SDK,which has a function to get all the data and pass it to the route.
$data = array(
"appCode" => $appCode,
"logo" => new \CURLFILE($request->logo),
"descriptionOfUse" => $request->descriptionOfUse,
"descriptionOfFetch" => $request->descriptionOfFetch,
"cancellationUrl" => $request->cancellationUrl ?? null,
"helpPageUrl" => $request->helpPageUrl,
"consentValidatityDays" => $request->consentValidatityDays ?? 0,
);
SDK File
public function addConsentRule($data)
{
$curl = curl_init();
dd($data);
curl_setopt_array($curl, array(
CURLOPT_PORT => $this->port,
CURLOPT_URL => $this->endPointUrl . "consentRule",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
// 'Content-Type: multipart/form-data;'
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// return $response;
return json_decode($response, true);
}
}
When I dd the variable which I am passing to the SDK it misses the mime and postname and the response is below
array:7 [
"appCode" => "2y105LSDDbI2ZML201a1VnrekOdIsA2SR06mWYhmIWZ3vsm4jE312S"
"logo" => CURLFile {#317
+name: "/tmp/phpUY9KmN"
+mime: ""
+postname: ""
}
"descriptionOfUse" => "use"
"descriptionOfFetch" => "fetch"
"cancellationUrl" => "uri"
"helpPageUrl" => "uri"
"consentValidatityDays" => "45"
]
Found the solution,might be helpful to someone.
getRealPath() ,will get the path.
getMimeType() ,will get the image type
getClientOriginalName() ,will get the file name
"logo" => new \CurlFile($request->logo->getRealPath(), $request->logo->getMimeType(), $request->logo->getClientOriginalName()),
Related
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 =)
I am trying to make a curl request!
Here I can make this request using postman and I am getting response perfectly using postman:
My Body parameter is: sub_domain
and my header is x-api-key value is something ZYWHUYAOSYSOASYYY
Ind i can get response perfectly!
But here want to make curl request on my end:
My Controller Code:
public function curlPost()
{
$data1 = [
'sub_domain' => 'value_1',
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://uwxcdwsc0k.execute-api.us-east-
1.amazonaws.com/prod/domain",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data1),
CURLOPT_HTTPHEADER => array(
// Set here required headers
"x-api-key: KiZTkTO9Ex2ZCOr7xmYRA4bInlJc9kVNrVN2INrc",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
print_r(json_decode($response));
}
}
and my Routes/api.php:
Route::post('subdomain', 'ApiController#curlPost');
and when i hit post request using postman i get error
stdClass Object
(
[code] => [422] Unprocessable Entity
[message] => sub_domain is required
)
Your help will be highly appreciated!
Add this to your header array,
'Content-Type:application/json'
Make the $data an array as below:
$data1 = array(
'sub_domain' => 'value_1'
);
Cheers
I have two array of objects that I want to post to an API but it displays an error missing value for parameter: productDC
it seems that i have to pass ProductDc and buyerDC along with their data. for this I also tried
$data_string = array({ProductDc"product_name" => "Electronics","price" => "200 usd"},
buyerDC{"buyer_name" => "john mark","address" => "17 more strret"});
below is the informations
1.) ProductDC
pass it as array of objects
**product_name(string)
price (string)**
2.) buyerDC
pass it as array of objects
**buyer_name(string)
address (string**)
here is my code
<?php
$data_string = array("product_name" => "Electronics","price" => "200 usd",
"buyer_name" => "john mark","address" => "17 more strret");
$data = json_encode($data_string);
//$data = $data_string;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "myapi.com",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"content-type: application/json; charset=utf-8"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
Considering below information that you have provided if they want a data in the format in which -
1.) ProductDC should be an array of objects containing -
product_name(string)
price (string)
2.) buyerDC should be array of objects containing-
buyer_name(string)
address (string)
Probably they are expecting the data in a different form which you may get by changing $data_string value as below -
$data_string = array(
"ProductDc"=>array(
"product_name" => "Electronics",
"price" => "200 usd"
),
"buyerDC"=>array(
"buyer_name" => "john mark",
"address" => "17 more strret"
)
);
Change your $data_string value to the one I posted above and check.
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;
}
?>
I want to pass a variable in CURLOPT_URL, here is my code
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.postmates.com/v1/customers/cus_KtQih0aARUZXdk/deliveries/$delivery_id/cancel",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
'pickup_address' => $_POST["pickup_address"],
'pickup_phone_number' => $_POST["pickup_phone_number"],
'pickup_name' => $_POST["pickup_name"],
'dropoff_address' => $_POST["dropoff_address"],
'dropoff_phone_number' => $_POST["dropoff_phone_number"],
'dropoff_name' => $_POST["dropoff_name"],
'manifest' => $_POST["manifest"]
),
CURLOPT_HTTPHEADER => array(
"authorization: Basic MjhiMDU0ODktNjdkYS00M2VhLTg0NmMtYWQ1MWQ2MGNmMDA1Og==",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=---011000010111000001101001",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
$delivery_id = trim($_POST['show_name']);
curl_close($curl);
$response = json_decode($response);
$timestamp = json_decode($dateJSON, true);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response->fee;
}
I want to add the variable $delivery_id in the url, but I am not too familiar with cURL and the above written code is not working. Please show me the way to include this variable in my url.
Once I had the same error. The solution is : use ' -apostrophe - and . -dot- before and after the variable. Like this:
/deliveries/'.$delivery_id.'/cancel