How to display binary data from curl in php How to display binary data from curl in php curl curl

How to display binary data from curl in php


never use the 'w' mode. it means the "text mode", because the default is, unfortunately, text mode.

on Windows, "text mode" means: whenever you try to write an \n byte (ascii 10, newline) and it's not preceded by an \r byte (ascii 13, carriage-return), insert an \r byte before writing the \n byte. (it also means text mode on linux/modern MacOS, but on Linux/modern MacOS, the text mode does absolutely nothing and is treated the same way as binary mode. * not true for classic MacOS <=9 from <=2001, on Classic MacOS, text mode did weird shit like it does weird shit on Windows)

always use the binary mode, eg wb, to make your program portable across both Windows and Linux

(actually modern versions of PHP automatically convert it to binary mode when not specified, but this question was asked in 2013, and this is still a very important rule-of-thumb if you ever use any other language than PHP. if you actually want text mode, explicitly enable text mode with wt, but you pretty much never want text mode, it's a horrible thing, made worse by the fact that it's the default mode for the underlying fopen() C api.. it's so horrible in fact, that Linux never supported it at all, and Apple/MacOS dropped support in 2001 with the release of MacOS X.. AFAIK Windows is the last major OS to actually support it, somethingsomething backwards-compatibility )


Here is how to send the file directly back to the user for download (uses your $content var):

$file_array = explode("\n\r", $content, 2);$header_array = explode("\n", $file_array[0]);foreach($header_array as $header_value) {$header_pieces = explode(':', $header_value);  if(count($header_pieces) == 2) {    $headers[$header_pieces[0]] = trim($header_pieces[1]);  }}header('Content-type: ' . $headers['Content-Type']);header('Content-Disposition: ' . $headers['Content-Disposition']);echo substr($file_array[1], 1);

There is a full example here:

http://ryansechrest.com/2012/07/send-and-receive-binary-files-using-php-and-curl/


Which php version are you using? Are you above PHP version 5.1.3? Then the CURLOPT_BINARYTRANSFER will have no effect.

Source: http://php.net/manual/en/function.curl-setopt.php

Looking at the file, you should add the following header to you're page:

header('Content-Type: image/png');