Wednesday, November 17, 2021

[SOLVED] PHP cURL: how to set body to binary data?

Issue

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

The command line equivalent of what I'm trying to achieve is:

curl --request POST --data-binary "@myimage.jpg" https://myapiurl

Solution

You can just set your body in 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 body.



Answered By - vfsoraki