Corrupted file after uploading througth curl
<p>I want to upload image file. Target is REST api endpoint with oAuth2 autohization. I managed to upload something but when I open file on server it's corrupted. Size didn't match with source file.</p>

<p>This is code that I use:</p>

<pre><code>&lt;?php
$file = 'example.jpg';

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, __DIR__.'/'.$file);

$ending = "\r\n";

$boundary = md5(microtime());
$fullBoundary = sprintf("--%s%s", $boundary, $ending);

$body = '';
$body .= $fullBoundary;
$body .= "Content-Disposition: form-data; name=\"image\"; filename=\"$file\"".$ending;
$body .= "Content-Type: $finfo".$ending;
$body .= "Content-Transfer-Encoding: base64".$ending.$ending;
$body .= chunk_split(base64_encode(file_get_contents(__DIR__.'/'.$file))).$ending;
$body .= "--".$boundary."--".$ending.$ending;
$ch = curl_init();
curl_setopt(
    $ch,
    CURLOPT_HTTPHEADER,
    [
        'Authorization: Bearer token...',
        "Content-Type: multipart/form-data; boundary=".$boundary,
    ]
);
curl_setopt($ch, CURLOPT_URL, "http://api.example.com/upload");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0');
$curl_response = curl_exec($ch);
print_r(curl_getinfo($ch));
print_r($curl_response);
curl_close($ch);
</code></pre>

<p>Can anyone help me with that?</p>

<p>P.S. I forget to say that I tried using "@" notation, and \CurlFile but then the $_FILES array was empty that's why I created whole request body manually.</p>