| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <?php
- /**
- * gmaps-key.php — Google Maps API key proxy
- * Serves the key only to same-origin requests.
- * Key is read from environment — never hardcoded in source.
- */
- declare(strict_types=1);
- $host = $_SERVER['HTTP_HOST'] ?? '';
- $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
- $referer = $_SERVER['HTTP_REFERER'] ?? '';
- $forwarded = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? '';
- $allowed = ['tasplanning.report', 'localhost', '127.0.0.1'];
- // Check all available headers — HTTP_HOST is always present via Apache
- $candidates = array_filter([
- parse_url('https://' . $host, PHP_URL_HOST),
- parse_url($origin, PHP_URL_HOST),
- parse_url($referer, PHP_URL_HOST),
- parse_url('https://' . $forwarded, PHP_URL_HOST),
- ]);
- $matched = false;
- foreach ($candidates as $c) {
- if (in_array(preg_replace('/:\d+$/', '', $c ?? ''), $allowed, true)) {
- $matched = true;
- break;
- }
- }
- if (!$matched) {
- http_response_code(403);
- header('Content-Type: application/json');
- echo json_encode(['error' => 'Forbidden', 'host' => $host, 'referer' => $referer]);
- exit;
- }
- // $_SERVER is more reliable than getenv() under Apache/mod_php
- $key = $_SERVER['GMAPS_API_KEY']
- ?? $_ENV['GMAPS_API_KEY']
- ?? getenv('GMAPS_API_KEY')
- ?: '';
- if (!$key) {
- http_response_code(503);
- header('Content-Type: application/json');
- echo json_encode(['error' => 'Key not configured']);
- exit;
- }
- header('Content-Type: application/json');
- header('Cache-Control: no-store, no-cache, must-revalidate');
- echo json_encode(['key' => $key]);
|