upload.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. header("Access-Control-Allow-Origin: *");
  3. header("Content-Type: application/json; charset=UTF-8");
  4. header("Access-Control-Allow-Methods: POST, OPTIONS");
  5. header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
  6. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  7. exit(0);
  8. }
  9. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  10. http_response_code(405);
  11. echo json_encode(array("message" => "Method not allowed."));
  12. exit;
  13. }
  14. if (!isset($_FILES['picture']) || $_FILES['picture']['error'] !== UPLOAD_ERR_OK) {
  15. http_response_code(400);
  16. echo json_encode(array("message" => "No file uploaded or upload error."));
  17. exit;
  18. }
  19. $uploadDir = 'uploads/';
  20. $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  21. $maxFileSize = 5 * 1024 * 1024; // 5MB
  22. if (!file_exists($uploadDir)) {
  23. mkdir($uploadDir, 0755, true);
  24. }
  25. $file = $_FILES['picture'];
  26. $fileType = $file['type'];
  27. $fileSize = $file['size'];
  28. $fileName = $file['name'];
  29. $tmpName = $file['tmp_name'];
  30. if (!in_array($fileType, $allowedTypes)) {
  31. http_response_code(400);
  32. echo json_encode(array("message" => "Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed."));
  33. exit;
  34. }
  35. if ($fileSize > $maxFileSize) {
  36. http_response_code(400);
  37. echo json_encode(array("message" => "File too large. Maximum size is 5MB."));
  38. exit;
  39. }
  40. $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
  41. $uniqueFileName = uniqid() . '.' . $fileExtension;
  42. $uploadPath = $uploadDir . $uniqueFileName;
  43. if (move_uploaded_file($tmpName, $uploadPath)) {
  44. $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
  45. $apiPath = dirname($_SERVER['PHP_SELF']);
  46. $fullUrl = $baseUrl . $apiPath . '/' . $uploadPath;
  47. http_response_code(200);
  48. echo json_encode(array(
  49. "message" => "File uploaded successfully.",
  50. "filename" => $uniqueFileName,
  51. "url" => $fullUrl
  52. ));
  53. } else {
  54. http_response_code(500);
  55. echo json_encode(array("message" => "Failed to upload file."));
  56. }
  57. ?>