Step 1: Backend (chatbot.php)
This PHP script will receive the user’s message via AJAX, call Gemini API, and return the response.
Add conversation memory so the Gemini chatbot remembers past messages in the same session.
We’ll use PHP $_SESSION to store the chat history and send it each time to the API.
Step 1: Update chatbot.php
<?php
session_start();
header("Content-Type: application/json");
// Your Gemini API Key
$apiKey = "YOUR_GEMINI_API_KEY";
// Get user message
$input = json_decode(file_get_contents("php://input"), true);
$userMessage = $input['message'] ?? "Hello";
// Initialize session chat history if not set
if (!isset($_SESSION['chat_history'])) {
$_SESSION['chat_history'] = [];
}
// Add user message to history
$_SESSION['chat_history'][] = [
"role" => "user",
"parts" => [["text" => $userMessage]]
];
// Prepare request payload (include full history)
$data = [
"contents" => $_SESSION['chat_history']
];
// cURL request to Gemini API
$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);
$responseData = json_decode($response, true);
// Extract bot reply
$botReply = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? "⚠️ No response from Gemini";
// Add bot reply to session history
$_SESSION['chat_history'][] = [
"role" => "model",
"parts" => [["text" => $botReply]]
];
// Return JSON
echo json_encode(["reply" => $botReply]);
Step 2: Keep index.html Same
No changes needed in the frontend — it already works. The only difference now is the bot remembers earlier messages in the conversation.
Step 3: Add “Reset Chat” Option (Optional)
In index.html, add a reset button:
<button onclick="resetChat()">Reset</button>
And update the script:
async function resetChat() {
const response = await fetch("reset.php", { method: "POST" });
document.getElementById("messages").innerHTML = "";
}
Step 4: Create reset.php
<?php session_start(); $_SESSION['chat_history'] = []; echo json_encode(["status" => "reset"]);