PHP cURL: how to set body to binary data?

I am using an API that wants me to send POST with binary data from a file as the request body. How can I accomplish this with PHP cURL?

Command line equivalent to what I'm trying to achieve:

curl --request POST --data-binary "@myimage.jpg" https://myapiurl 
+4
source share
4 answers

You can simply set your body to CURLOPT_POSTFIELDS .

Example:

 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://url/url/url" ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_POST, 1 ); curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" ); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain')); $result=curl_exec ($ch); 

Taken from here

Of course, set your own header type and just do file_get_contents('/path/to/file') for the body.

+14
source

Try the following:

 $postfields = array( 'upload_file' => '@'.$tmpFile ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url.'/instances'); curl_setopt($ch, CURLOPT_POST, 1 ); curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^ curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $postResult = curl_exec($ch); if (curl_errno($ch)) { print curl_error($ch); } curl_close($ch); 
0
source

This can be done through an instance of CURLFile:

 $uploadFilePath = __DIR__ . '/resource/file.txt'; if (!file_exists($uploadFilePath)) { throw new Exception('File not found: ' . $uploadFilePath); } $uploadFileMimeType = mime_content_type($uploadFilePath); $uploadFilePostKey = 'file'; $uploadFile = new CURLFile( $uploadFilePath, $uploadFileMimeType, $uploadFilePostKey ); $curlHandler = curl_init(); curl_setopt_array($curlHandler, [ CURLOPT_URL => 'https://postman-echo.com/post', CURLOPT_RETURNTRANSFER => true, /** * Specify POST method */ CURLOPT_POST => true, /** * Specify array of form fields */ CURLOPT_POSTFIELDS => [ $uploadFilePostKey => $uploadFile, ], ]); $response = curl_exec($curlHandler); curl_close($curlHandler); echo($response); 

See - https://github.com/andriichuk/php-curl-cookbook#upload-file

0
source

You need to provide the appropriate header to send the POST with binary data.

 $header = array('Content-Type: multipart/form-data'); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($resource, CURLOPT_POSTFIELDS, $arr_containing_file); 

For example, your $ arr_containing_file may contain the file as expected (I mean, you need to provide the corresponding expected field with the API service).

 $arr_containing_file = array('datafile' => '@inputfile.ext'); 
-one
source

All Articles