Skip to content

Instantly share code, notes, and snippets.

@nodirshox
Last active September 17, 2021 04:35
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 nodirshox/28699beb011b5c20c1887ae2ef4b61a1 to your computer and use it in GitHub Desktop.
Save nodirshox/28699beb011b5c20c1887ae2ef4b61a1 to your computer and use it in GitHub Desktop.
<?php
// PHP REST API FILE UPLOAD
// source: https://www.onlyxcodes.com/2021/03/php-rest-api-file-upload.html
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization");
$data = json_decode(file_get_contents("php://input"), true); // collect input parameters and convert into readable format
$fileName = $_FILES['file']['name'];
$tempPath = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$errorMSG = json_encode(array("message" => "Method not found", "status" => false));
http_response_code(404);
echo $errorMSG;
} else {
if (empty($fileName)) {
$errorMSG = json_encode(array("message" => "Please select file", "status" => false));
http_response_code(400);
echo $errorMSG;
} else {
$timestamp = new DateTime();
$newFileName = $timestamp->getTimestamp();
$fileName = str_replace(' ', '-', $fileName);
$fileName = "{$newFileName}-{$fileName}";
$upload_path = 'files/'; // set upload folder path
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); // get file extension
// invalid file extensions
$valid_extensions = array('php', 'sql');
// do not allow invalid file formats
if (in_array($fileExt, $valid_extensions)) {
$errorMSG = json_encode(array("message" => "Forbidden file type: {$fileExt}", "status" => false));
http_response_code(400);
echo $errorMSG;
} else {
// check file size '2MB', default max limit is 2MB, if you want increase, configure php server
if ($fileSize < 2000000 && $fileSize > 0){
move_uploaded_file($tempPath, $upload_path . $fileName); // move file from system temporary path to our upload folder path
} else {
$errorMSG = json_encode(array("message" => "Sorry, your file is too large, please upload 2 MB size", "status" => false));
http_response_code(400);
echo $errorMSG;
}
}
}
// if no error caused, continue
if (!isset($errorMSG)) {
echo json_encode(array("message" => "File uploaded successfully", "status" => true, "name" => "{$upload_path}{$fileName}", "url" => "https://your-site.com/{$upload_path}{$fileName}"));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment