Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP cURL: how to set body to binary data?

Tags:

php

curl

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
like image 622
Nocklas Avatar asked Aug 12 '15 16:08

Nocklas


People also ask

How does cURL send binary data?

You probably request this: -F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc.

Does PHP use binary content?

PHP has functions to convert a binary stream of data into individual values, but for whole streams in a specific format, parsing data may be a complicated task.

What is Curl_init PHP?

The curl_init() function will initialize a new session and return a cURL handle. curl_exec($ch) function should be called after initialize a cURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by ch).

What is Curlopt_postfields?

CURLOPT_POSTFIELDS. The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'.


3 Answers

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.

like image 68
vfsoraki Avatar answered Oct 18 '22 03:10

vfsoraki


This can be done through CURLFile instance:

$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

like image 27
Serhii Andriichuk Avatar answered Oct 18 '22 04:10

Serhii Andriichuk


to set body to binary data and upload without multipart/form-data, the key is to cheat curl, first we tell him to PUT, then to POST:

    <?php
    
    $file_local_full = '/tmp/foobar.png';
    $content_type = mime_content_type($file_local_full);

    $headers = array(
        "Content-Type: $content_type", // or whatever you want
    );

    $filesize = filesize($file_local_full);
    $stream = fopen($file_local_full, 'r');

    $curl_opts = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_PUT => true,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_INFILE => $stream,
        CURLOPT_INFILESIZE => $filesize,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
    );

    $curl = curl_init();
    curl_setopt_array($curl, $curl_opts);

    $response = curl_exec($curl);

    fclose($stream);

    if (curl_errno($curl)) {
        $error_msg = curl_error($curl);
        throw new \Exception($error_msg);
    }

    curl_close($curl);

credits: How to POST a large amount of data within PHP curl without memory overhead?

like image 33
Sergio A. Kessler Avatar answered Oct 18 '22 03:10

Sergio A. Kessler