-
Notifications
You must be signed in to change notification settings - Fork 2k
/
server.php
42 lines (37 loc) · 1.67 KB
/
server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
}
//Make sure you remove those you do not want to support
header('Access-Control-Allow-Origin: *');
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
//Just exit with 200 OK with the above headers for OPTIONS method
exit(0);
}
if ($_POST && !empty($_FILES["file"])) {
$target_dir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';
$target_file = $target_dir . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
try {
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
$data = ['url' => $target_file, 'message' => 'The file ' . basename($_FILES['file']['name']) . ' has been uploaded.'];
http_response_code(201);
echo json_encode($data);
} else {
throw new Exception('Unable to move the uploaded file to its final location:' . $target_file);
}
} catch (\Throwable $th) {
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
$data = ['message' => 'Sorry, there was an error uploading your file.', 'error' => $th->getMessage()];
http_response_code(400);
echo json_encode($data);
}
}