Skip to content

Commit a3cb1d7

Browse files
authored
Create php-rest-api-file-upload.php
1 parent 08cae34 commit a3cb1d7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
header("Acess-Control-Allow-Origin: *");
4+
header("Content-Type: application/json");
5+
header("Acess-Control-Allow-Methods: POST");
6+
header("Acess-Control-Allow-Headers: Acess-Control-Allow-Headers,Content-Type,Acess-Control-Allow-Methods, Authorization");
7+
8+
$data = json_decode(file_get_contents("php://input"), true); // collect input parameters and convert into readable format
9+
10+
$fileName = $_FILES['sendfile']['name'];
11+
$tempPath = $_FILES['sendfile']['tmp_name'];
12+
$fileSize = $_FILES['sendfile']['size'];
13+
14+
if(empty($fileName)) {
15+
echo json_encode(array("message" => "please select a file", "status" => false));
16+
} else {
17+
$upload_path = 'upload/'; // set upload folder path
18+
19+
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); // get file extension
20+
21+
// valid file extensions
22+
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'pdf', 'docx', 'txt');
23+
24+
// allow valid file formats
25+
if(in_array($fileExt, $valid_extensions)) {
26+
//check file does not exist in the upload folder path
27+
if(!file_exists($upload_path . $fileName)) {
28+
// check file size '5MB'
29+
if($fileSize < 5000000) {
30+
if(move_uploaded_file($tempPath, $upload_path . $fileName)) { // move file from system temporary path to the upload folder path
31+
echo json_encode(array("message" => "File Uploaded Successfully", "status" => true));
32+
} else {
33+
echo json_encode(array("message" => "File couldn't be uploaded", "status" => false));
34+
}
35+
} else {
36+
echo json_encode(array("message" => "Sorry, your file is too large, please upload 5 MB size", "status" => false));
37+
}
38+
} else {
39+
echo json_encode(array("message" => "Sorry, file already exists check upload folder", "status" => false));
40+
}
41+
} else {
42+
echo json_encode(array("message" => "Sorry, only JPG, JPEG, PNG, GIF, PDF, DOCX &amp; TEXT files are allowed", "status" => false));
43+
}
44+
}
45+

0 commit comments

Comments
 (0)