Last Updated: February 25, 2016
·
707
· iaincampbell

Handling image uploads from a JSON payload

This is for a PHP web service that receives one of two POST payloads:

  1. A standard HTTP POST (multipart/form-data)
  2. A POST of JSON data (content-type application/json)

In the second case, images are sent as base64-encoded strings. The code below strips the metadata from the start of the file and creates a temporary file to replace that in the $_FILES array.

In this particular case, all JSON data was being sent from a remote Python web service, so the user agent check was tailored appropriately.

if(strstr($_SERVER['HTTP_USER_AGENT'], 'CPython')!==false) {
    $data = file_get_contents($_FILES['upfile']['tmp_name']);
    // Strip the meta-data from the start of the file
    // This is added when base64-encoding the data
    $data = substr($data, strpos($data, ','), strlen($data));
    $data = base64_decode($data);
    $temp = tempnam("/tmp", "img_");
    file_put_contents($temp, $data);
    $_FILES['upfile']['tmp_name'] = $temp;
}

We re-assign the value of $_FILES['upfile']['tmp_name'] for future handling.

NB

When you move the file, you need to use rename() in place of move_uploaded_file() as it's no longer an uploaded file.

if(!rename($temp, $new_filename)) {
    unlink($temp); // clean up
    $app->halt(500, 'Internal Server Error. ' . $temp . ' ' . $new_filename);
}