200], $data));
}
function error(string $message)
{
return response([‘code’ => 500, ‘message’ => $message]);
}
function notfound()
{
return response([‘code’ => 404, ‘message’ => ‘Not found’]);
}
function main()
{
$httpPath = parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH);
$httpMethod = $_SERVER[‘REQUEST_METHOD’];
$allowedExtensions = [‘txt’, ‘pdf’, ‘png’, ‘jpg’];
header(‘Access-Control-Allow-Origin: *’);
header(‘Content-Type: appplication/json’);
if (HttpMethod::POST === $httpMethod) {
if (‘/upload’ === $httpPath) {
if (isset($_FILES[‘profileImage’]))
{
$tmpName = $_FILES[‘profileImage’][‘tmp_name’];
$clientName = $_FILES[‘profileImage’][‘name’];
$extension = pathinfo($clientName, PATHINFO_EXTENSION);
$serverName = sprintf(“%s/%s.%s”, FILES_STORAGE_PATH, md5($clientName), $extension);
$uploadErrorCode = $_FILES[‘profileImage’][‘error’];
if(!in_array($extension, $allowedExtensions, 1)) {
return error(‘Extension not allowed’);
}
if(move_uploaded_file($tmpName, $serverName))
{
return ok([‘message’ => ‘File uploaded’, ‘filename’ => $serverName]);
}
else if($uploadErrorCode > 0)
{
$fileUploadErrorsMap = [
UPLOAD_ERR_INI_SIZE => ‘The file exceeds the upload_max_filesize setting in php.ini.’,
UPLOAD_ERR_FORM_SIZE => ‘The file exceeds the MAX_FILE_SIZE setting in the HTML form.’,
UPLOAD_ERR_PARTIAL => ‘The file was only partially uploaded.’,
UPLOAD_ERR_NO_FILE => ‘No file was uploaded.’,
UPLOAD_ERR_NO_TMP_DIR => ‘No temporary folder was available.’,
UPLOAD_ERR_CANT_WRITE => ‘Unable to write to the disk.’,
UPLOAD_ERR_EXTENSION => ‘File upload stopped.’
];
$errorMessage = $fileUploadErrorsMap[$uploadErrorCode] ?: ‘A system error occurred.’;
return error($errorMessage);
}
} else {
return error(‘No file param’);
}
} else {
return notfound();
}
}
if (HttpMethod::GET === $httpMethod) {
return response([‘code’ => 200, ‘message’ => ‘No data’]);
}
}
print main();