Handling image uploads from a JSON payload
This is for a PHP web service that receives one of two POST payloads:
- A standard HTTP POST (multipart/form-data)
- 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);
}
Written by Iain Campbell
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#