2

I have to send files from my php back end to an API as form-data objects. These files were created directly in the back end and the sending is not associated with any HTML form.

The API documentation provides an example of sending a form-data object but in python, here it is:

files=[
  ('file',('owl-50267_1920.jpg',open('dataset/img/owl-1.jpg','rb')))
]

How can I do the same thing in php ? Thank you

0

1 Answer 1

0

Here is how to create a form-data object in PHP:

$file = ['file' => new CURLFILE('path/to/file.ext')];

Example of usage:

<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => 'API endpoint URL',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => ['file' => new CURLFILE('path/to/file.ext')],
  CURLOPT_HTTPHEADER => ['X-API-KEY': 'api key']
]);

$response = curl_exec($curl);

curl_close($curl);
echo $response;

=> See previous answer here: Send file using multipart/form-data request in php

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.