server.php 1.7 KB

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