PHP cURL: how to set body to binary data?

PHP cURL: how to set body to binary data?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP cURL: How to Set Body to Binary Data

When interacting with REST APIs, you often encounter endpoints that expect raw binary payloads rather than standard text strings. The command-line equivalent curl --data-binary "@myimage.jpg" demonstrates the straightforward approach: load a file and send it exactly as bytes without attempting any textual encoding. Translating this behavior directly to PHP's cURL extension requires careful attention to how the library handles string boundaries and content types.

The most common mistake developers make is assuming that passing a binary file path or base64-encoded string to curl_setopt with CURLOPT_POSTFIELDS will automatically handle the data correctly. If you simply pass a raw string containing non-UTF-8 bytes, PHP might attempt to encode it as UTF-8 before sending, corrupting the payload. Similarly, passing a file path without specific flags can lead PHP to read the file and treat the content as a string, potentially adding unwanted line endings or altering the header's Content-Type.

To replicate the behavior of --data-binary, you must explicitly instruct cURL not to perform any automatic encoding on the body. The primary mechanism for this is setting the CURLOPT_POSTFIELDS option to point directly to the file resource using the @filename syntax. This tells cURL to treat the subsequent argument as a file path, reading the raw bytes into the request body exactly as they exist on disk.

$ch = curl_init('https://myapiurl');

// Set the binary flag and specify the file directly
curl_setopt($ch, CURLOPT_POSTFIELDS, '@myimage.jpg');

// Ensure headers are sent correctly if not using default behavior
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/octet-stream' 
]);

$response = curl_exec($ch);

While the @filename syntax is powerful, it automatically sets a Content-Type header based on the file extension or defaults to application/octet-stream. This is usually desirable for binary uploads. However, if your API requires a specific MIME type regardless of the file extension, you should override this behavior by providing a custom header array alongside the field data.

A critical pitfall involves how cURL handles large files in memory versus streaming them directly from disk. By default, CURLOPT_POSTFIELDS loads the entire content into a string buffer before sending it. For small files like configuration snippets or images under a few megabytes, this is negligible. However, with very large binary datasets, loading everything into RAM increases memory usage significantly.

To mitigate this for massive uploads, you can use the CURLOPT_INFILE option combined with a file pointer. This allows cURL to stream data directly from the file handle without buffering the entire payload in memory first. The syntax changes slightly; instead of using the @filename shorthand, you pass an open file resource and set the length limit separately if needed.

$fp = fopen('mylargefile.bin', 'rb'); // Open in binary read mode

curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('mylargefile.bin'));
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); // Empty string for streaming

// Ensure the file pointer is closed after execution to prevent resource leaks
curl_exec($ch); 
fclose($fp);

It is also essential to ensure that CURLOPT_RETURNTRANSFER is set appropriately. If you intend to process the raw response bytes (common in binary API interactions), setting this option returns the response as a string rather than converting it directly to an output stream. This ensures that subsequent processing of the $response variable remains consistent whether the request succeeded or failed.

Finally, always verify that the CURLOPT_TIMEOUT is set if your application runs on long-lived processes. Binary transfers can be slower due to network latency and chunking overhead. Without a timeout, a stalled upload could hold open file descriptors indefinitely, leading to resource exhaustion in high-concurrency environments. By adhering to these patterns, you ensure that PHP cURL behaves predictably when handling raw binary data, mirroring the robustness of the command-line tool while maintaining full programmatic control over headers and streams.

Our network