Maybe someone can help me? I do not get on with this problem
I have a POST array from a formualar and a file already existing on the server.
The task is to send the POST data and the file via CURL PUT to a URL.
I’ve been trying to solve the problem for hours/days now
I have set the header Content-type: application/octet-stream
and the fields with $ch->setOption(CURLOPT_POSTFIELDS, http_build_query($data)
The POST data looks like this:
$data = array (
'field1' => 'lorem',
'field2' => 'ipsum',
'field3' => 'dolor'
);
Using instructions (php.net, stackoverflow etc.)
https://kb.detlus.com/articles/php/upload-files-using-curl/
https://www.php.net/manual/de/curlfile.construct.php
Is it possible to use cURL to stream upload a file using POST?
I try to send the file
Does not work
$data = array (
'field1' => 'lorem',
'field2' => 'ipsum',
'field3' => 'dolor'
'file' => '@'.realpath('/abs/path/file.xlsx');
);
neither
$data = array (
'field1' => 'lorem',
'field2' => 'ipsum',
'field3' => 'dolor'
);
$data['file'] = curl_file_create('/abs/path/file.xlsx'], mime_content_type('/abs/path/file.xlsx'), 'file.xlsx');
this leads to the following array
$data = array (
'field1' => 'lorem',
'field2' => 'ipsum',
'field3' => 'dolor',
'file' =>
array (
'file' =>
CURLFile::__set_state(array(
'name' => '/abs/path/file.xlsx',
'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'postname' => '/abs/path/file.xlsx',
)),
)
);
Depending on the version I try I get a 400 or 500 error.
Does anyone have a tip that can help me?
What am I doing wrong?
2
Answers
Thanks for your help!!! Solution =>
Content-Type: multipart/form-data
I think the main problem here is that you’re using the wrong content type.
For file uploads you should be using "Content-Type: multipart/form-data".
Taken from Wikipedia (in the multipart subtypes) MIME
I wrote this snippet, hope this can help you (sorry for the non-OOP version of the code, I don’t have a PHP 8 install, I’m using PHP 7.4, but you can "translate" it easily :D):
I really hope this can help, unfortunately I don’t know the URL/API you’re submitting the request to so I can’t test it on your endpoint. I made an endpoint myself:
The output I got showed me all the fields and the file upload.