router.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. // Router for PHP built-in server
  3. $request_uri = $_SERVER['REQUEST_URI'];
  4. $request_method = $_SERVER['REQUEST_METHOD'];
  5. // Remove query string from request URI
  6. $path = parse_url($request_uri, PHP_URL_PATH);
  7. // Set CORS headers
  8. header("Access-Control-Allow-Origin: *");
  9. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  10. header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
  11. // Handle OPTIONS requests
  12. if ($request_method == 'OPTIONS') {
  13. exit(0);
  14. }
  15. // Route API requests
  16. if (strpos($path, '/api/') === 0) {
  17. // Extract the API file path
  18. $api_file = substr($path, 5); // Remove '/api/' prefix
  19. // Add .php extension if not present
  20. if (!strpos($api_file, '.php')) {
  21. $api_file .= '.php';
  22. }
  23. // Construct full file path
  24. $file_path = __DIR__ . '/api/' . $api_file;
  25. // Check if file exists
  26. if (file_exists($file_path)) {
  27. include $file_path;
  28. } else {
  29. // Return 404 for non-existent API endpoints
  30. http_response_code(404);
  31. echo json_encode(array("message" => "API endpoint not found"));
  32. }
  33. } else {
  34. // Serve static files or return 404
  35. $file_path = __DIR__ . $path;
  36. if ($path === '/' || $path === '/index.html') {
  37. // Serve a simple index page
  38. http_response_code(200);
  39. echo "<h1>Inventory API Server</h1>";
  40. echo "<p>API is running on port 8080</p>";
  41. echo "<p>Available endpoints:</p>";
  42. echo "<ul>";
  43. echo "<li><a href='/api/auth.php'>/api/auth.php</a></li>";
  44. echo "<li><a href='/api/items.php'>/api/items.php</a></li>";
  45. echo "<li><a href='/api/clients.php'>/api/clients.php</a></li>";
  46. echo "<li><a href='/api/invoices.php'>/api/invoices.php</a></li>";
  47. echo "</ul>";
  48. } elseif (file_exists($file_path) && is_file($file_path)) {
  49. // Serve static files
  50. $mime_types = array(
  51. 'css' => 'text/css',
  52. 'js' => 'application/javascript',
  53. 'json' => 'application/json',
  54. 'html' => 'text/html',
  55. 'txt' => 'text/plain'
  56. );
  57. $extension = pathinfo($file_path, PATHINFO_EXTENSION);
  58. if (isset($mime_types[$extension])) {
  59. header("Content-Type: " . $mime_types[$extension]);
  60. }
  61. readfile($file_path);
  62. } else {
  63. // Return 404 for other requests
  64. http_response_code(404);
  65. echo json_encode(array("message" => "Not found"));
  66. }
  67. }
  68. ?>