server.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. ini_set('display_errors', 1);
  3. ini_set('display_startup_errors', 1);
  4. error_reporting(E_ALL);
  5. // Get the maximum upload file size
  6. $max_size = ini_get('upload_max_filesize');
  7. if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  8. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  9. header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
  10. }
  11. //Make sure you remove those you do not want to support
  12. header('Access-Control-Allow-Origin: *');
  13. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  14. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  15. }
  16. //Just exit with 200 OK with the above headers for OPTIONS method
  17. exit(0);
  18. }
  19. if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES["file"])) {
  20. $target_dir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';
  21. $file_name = basename($_FILES['file']['name']);
  22. $file_size = $_FILES['file']['size'];
  23. $target_file = $target_dir . DIRECTORY_SEPARATOR . $file_name;
  24. // Validate file size
  25. if ($file_size > $max_size) {
  26. header('Access-Control-Allow-Origin: *');
  27. header('Content-type: application/json');
  28. $data = ['message' => 'File size exceeds the maximum allowed size of ' . $max_size . '.'];
  29. http_response_code(400);
  30. echo json_encode($data);
  31. exit;
  32. }
  33. // Sanitize file name to prevent directory traversal attacks
  34. $file_name = preg_replace('/[^a-zA-Z0-9._-]/', '', $file_name);
  35. $target_file = $target_dir . DIRECTORY_SEPARATOR . $file_name;
  36. try {
  37. if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
  38. header('Access-Control-Allow-Origin: *');
  39. header('Content-type: application/json');
  40. $data = ['url' => $target_file, 'message' => 'The file ' . $file_name . ' has been uploaded.'];
  41. http_response_code(201);
  42. echo json_encode($data);
  43. } else {
  44. throw new Exception('Unable to move the uploaded file to its final location:' . $target_file);
  45. }
  46. } catch (\Throwable $th) {
  47. header('Access-Control-Allow-Origin: *');
  48. header('Content-type: application/json');
  49. $data = ['message' => 'Sorry, there was an error uploading your file.', 'error' => $th->getMessage()];
  50. http_response_code(400);
  51. echo json_encode($data);
  52. }
  53. } else {
  54. header('Access-Control-Allow-Origin: *');
  55. header('Content-type: application/json');
  56. $data = ['message' => 'Please upload a file.'];
  57. http_response_code(400);
  58. echo json_encode($data);
  59. }