Hand coding a multi-part request and POSTing

Posting a quick note to myself about how to hand to handcode a multipart request. Required for a REST server/client that I am currently writing. I needed this so that I can post a json object and the associated image in the same post without the typical php name=value paradigm and read from the php://input stream.
However the effort of parsing and un-parsing multipart messages makes me wonder if its just easier to base64 encode the file and send it part of the json object and then un-serialize it at the other end. Shall write more about it later.

$mime_boundary = md5(time());
$data = '--' . $mime_boundary . PHP_EOL;
$data .= 'Content-Disposition: form-data; name="data"' . PHP_EOL . PHP_EOL;
$data .= "Some Data" . PHP_EOL;
$data .= '--' . $mime_boundary . PHP_EOL;
$data .= 'Content-Disposition: form-data; name="logo"; filename="secretfile.jpg"' . PHP_EOL;
$data .= 'Content-Type: image/jpeg' . PHP_EOL;
$data .= 'Content-Transfer-Encoding: base64' . PHP_EOL . PHP_EOL;
$data .= chunk_split(base64_encode($file)) . PHP_EOL;
$data .= "--" . $mime_boundary . "--" . PHP_EOL . PHP_EOL; // finish with two eol's!!
die($data);
$params = array('http' => array(
                  'method' => 'POST',
                  'header' => 'Content-Type: multipart/form-data; boundary=' . $mime_boundary . PHP_EOL,
                  'content' => $data
               ));

$ctx = stream_context_create($params);
$response = file_get_contents($server, FILE_TEXT, $ctx);
print '--- printing out response ---' . PHP_EOL;
print_r($response);

About rp

Architect for large, highly scalable LAMP applications and Technical Manager with special focus on metrics based continuous improvement of teams and products. Rajat has close to a decade of experience of a very wide range of skills related to infrastructure, middleware, app servers all the way to front-end technologies and software development methodologies including agile, iterative waterfall, waterfall as well as ah-hoc startup using the right approach in the right context to reduce time to market.