5

I'm trying to upload a file AND json data in a curl request in PHP. The request works fine with curl in command line. This is the curl request in command line :

curl -v --basic -u'username' -F file="@documentTest.pdf;type=application/octet-stream" -F data='{"nomDocument":"test.pdf","externalid":"123456"};type=application/json' https://server.com/api/sendDocument

The header is set to multipart/form-data and I would like to set the mime type for each item sent in the request : application/octet-stream for the file AND application/json for json data.

This is my PHP code

$dataJson = '{"nomDocument":"test.pdf","externalid":"123456"}';

$header = array('Authorization: Basic c2fghEfgfhVDZkOWxfghfghfgUy', 'Content-Type: multipart/form-data');

$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt(
    $ch, CURLOPT_POSTFIELDS, array(
        'file' => new \CurlFile(realpath('documentTest.pdf'), 'application/octet-stream', 'test.pdf'),
        'data' => $dataJson
    )
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, 'https://server.com/api/sendDocument');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // false for https
$page_content = curl_exec($ch);
curl_close($ch);

How to set application/json for data in the CURLOPT_POSTFIELDS ?

Thank you.

jeje
  • 121
  • 1
  • 2
  • 7

0 Answers0