gmaps-key.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /**
  3. * gmaps-key.php — Google Maps API key proxy
  4. * Serves the key only to same-origin requests.
  5. * Key is read from environment — never hardcoded in source.
  6. */
  7. declare(strict_types=1);
  8. $host = $_SERVER['HTTP_HOST'] ?? '';
  9. $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
  10. $referer = $_SERVER['HTTP_REFERER'] ?? '';
  11. $forwarded = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? '';
  12. $allowed = ['tasplanning.report', 'localhost', '127.0.0.1'];
  13. // Check all available headers — HTTP_HOST is always present via Apache
  14. $candidates = array_filter([
  15. parse_url('https://' . $host, PHP_URL_HOST),
  16. parse_url($origin, PHP_URL_HOST),
  17. parse_url($referer, PHP_URL_HOST),
  18. parse_url('https://' . $forwarded, PHP_URL_HOST),
  19. ]);
  20. $matched = false;
  21. foreach ($candidates as $c) {
  22. if (in_array(preg_replace('/:\d+$/', '', $c ?? ''), $allowed, true)) {
  23. $matched = true;
  24. break;
  25. }
  26. }
  27. if (!$matched) {
  28. http_response_code(403);
  29. header('Content-Type: application/json');
  30. echo json_encode(['error' => 'Forbidden', 'host' => $host, 'referer' => $referer]);
  31. exit;
  32. }
  33. // $_SERVER is more reliable than getenv() under Apache/mod_php
  34. $key = $_SERVER['GMAPS_API_KEY']
  35. ?? $_ENV['GMAPS_API_KEY']
  36. ?? getenv('GMAPS_API_KEY')
  37. ?: '';
  38. if (!$key) {
  39. http_response_code(503);
  40. header('Content-Type: application/json');
  41. echo json_encode(['error' => 'Key not configured']);
  42. exit;
  43. }
  44. header('Content-Type: application/json');
  45. header('Cache-Control: no-store, no-cache, must-revalidate');
  46. echo json_encode(['key' => $key]);