Requirements
-
PHP 7.4+
-
cURL enabled in PHP
-
Gemini API Key (from Google AI Studio: https://makersuite.google.com/app)
Step 1: Setup Your PHP Environment
Create a PHP file, e.g., chatbot.php.
Step 2: Write the Gemini API Chat Code in PHP
Here’s a simple example:
<?php
$apiKey = 'YOUR_GEMINI_API_KEY'; // Replace with your actual API key
$prompt = "Hello, how can I help you today?";
$data = [
"contents" => [
[
"role" => "user",
"parts" => [
["text" => $prompt]
]
]
]
];
$ch = curl_init('https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . $apiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
]);
$response = curl_exec($ch);
curl_close($ch);
// Handle response
$responseData = json_decode($response, true);
$botReply = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? "No response";
echo "<strong>Bot:</strong> " . htmlspecialchars($botReply);
Step 3: Test
Put this on a local server or a live PHP-compatible host and access the file in the browser.
Optional: Add a Simple HTML Form for User Input
<form method="post">
<input type="text" name="prompt" placeholder="Say something..." required>
<button type="submit">Send</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['prompt'])) {
$userPrompt = $_POST['prompt'];
// use $userPrompt in the API call above
}
?>