'Nur POST-Anfragen sind erlaubt.']); exit; } // 3. API-Schlüssel sicher aus .env laden $apiKey = ''; $envFiles = [__DIR__ . '/.env', __DIR__ . '/../home/.env']; foreach ($envFiles as $envFile) { if (file_exists($envFile)) { foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) { $line = trim($line); if ($line === '' || $line[0] === '#') continue; if (strpos($line, '=') !== false) { list($k, $v) = explode('=', $line, 2); if (trim($k) === 'GEMINI_API_KEY') { $apiKey = trim(trim($v), '"\''); break 2; } } } } } if (empty($apiKey)) { http_response_code(500); echo json_encode(['error' => 'API-Schlüssel nicht konfiguriert.']); exit; } // 4. Lese die JSON-Daten, die vom Frontend (JavaScript) gesendet wurden. $json_input = file_get_contents('php://input'); $request_data = json_decode($json_input, true); // Überprüfen, ob die Daten korrekt sind if (json_last_error() !== JSON_ERROR_NONE || !isset($request_data['apiUrl']) || !isset($request_data['payload'])) { http_response_code(400); // Bad Request echo json_encode(['error' => 'Ungültige Anfrage-Daten.']); exit; } $apiUrl = $request_data['apiUrl']; $payload = $request_data['payload']; // SSRF-Schutz: Nur generativelanguage.googleapis.com erlauben $parsed = parse_url($apiUrl); if (!isset($parsed['host']) || $parsed['host'] !== 'generativelanguage.googleapis.com') { http_response_code(403); echo json_encode(['error' => 'Ungültiges API-Ziel.']); exit; } // 5. Baue die vollständige URL für die Google API zusammen. $fullApiUrl = $apiUrl . '?key=' . $apiKey; // 6. Sende die Anfrage mit cURL an die Google API (Standardmethode in PHP). $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $fullApiUrl, CURLOPT_RETURNTRANSFER => true, // Gib die Antwort als String zurück CURLOPT_POST => true, // Es ist eine POST-Anfrage CURLOPT_POSTFIELDS => json_encode($payload), // Der JSON-Body der Anfrage CURLOPT_HTTPHEADER => [ // Wichtige Header setzen 'Content-Type: application/json', ], ]); // Führe die Anfrage aus $response_body = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Hole den HTTP-Statuscode der Antwort // Prüfe auf Fehler bei der cURL-Anfrage selbst if (curl_errno($ch)) { http_response_code(500); echo json_encode(['error' => 'Fehler bei der Weiterleitung der Anfrage: ' . curl_error($ch)]); exit; } curl_close($ch); // 7. Leite die Antwort von Google direkt an dein Frontend weiter. // Setze den HTTP-Statuscode auf den gleichen, den wir von Google bekommen haben. http_response_code($http_code); echo $response_body; ?>