Skip to content

Instantly share code, notes, and snippets.

@nklatt
Created April 6, 2022 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nklatt/5f2c3a849ff9dfb9914bd42faf9ad5bd to your computer and use it in GitHub Desktop.
Save nklatt/5f2c3a849ff9dfb9914bd42faf9ad5bd to your computer and use it in GitHub Desktop.
Basic post handler as a HTTP response code example.
<?php
$status = 500; // if we don't change this then the problem is this code
$result = array();
if (empty($_FILES['file']['tmp_name'])) {
$status = 400;
$result['message'] = 'No file found.';
} else if (empty($_FILES['file']['name'])) {
$status = 400;
$result['message'] = 'No file name found.';
} else if (!file_exists($_FILES['file']['tmp_name'])) {
$status = 400;
$result['message'] = 'File not found.';
} else {
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($extension, array('jpeg', 'jpg')) {
$status = 415;
$result['message'] = 'Unsupported file type.';
}
else if (empty($_REQUEST['uid'])) {
$status = 400;
$result['message'] = 'Missing unique ID';
} else {
$filesFolder = DIR_BASE.'/files/uploads/images';
if (!is_dir($filesFolder)) {
mkdir($filesFolder, 0777, true);
}
if (!is_dir($filesFolder)) {
$status = 500;
$result['message'] = 'Unable to create directory';
} else {
if (!move_uploaded_file($_FILES['file']['tmp_name'], $filesFolder.'/'.$_FILES['file']['name'])) {
$status = 500;
$result['message'] = 'Unable to move file into place.';
} else {
// Success!
$status = 200;
$result['name'] = $_FILES['file']['name'];
}
}
}
}
}
http_response_code($status);
echo json_encode($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment