full interactive chatbot using PHP (backend) + HTML/CSS + JavaScript (frontend) with the Gemini API.

Step 1: Backend (chatbot.php)

This PHP script will receive the user’s message via AJAX, call Gemini API, and return the response.

<?php
header("Content-Type: application/json");

// Your Gemini API Key
$apiKey = "YOUR_GEMINI_API_KEY";

// Get user message from AJAX
$input = json_decode(file_get_contents("php://input"), true);
$userMessage = $input['message'] ?? "Hello";

// Prepare request payload
$data = [
    "contents" => [
        [
            "role" => "user",
            "parts" => [
                ["text" => $userMessage]
            ]
        ]
    ]
];

// cURL request
$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";

// Return JSON
echo json_encode(["reply" => $botReply]);


Step 2: Frontend (index.html)

This will be your chatbot UI.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Gemini Chatbot</title>
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0A%20%20%20%20body%20%7B%20font-family%3A%20Arial%2C%20sans-serif%3B%20background%3A%20%23f4f4f9%3B%20display%3A%20flex%3B%20justify-content%3A%20center%3B%20padding%3A%2030px%3B%20%7D%0A%20%20%20%20.chatbox%20%7B%20width%3A%20400px%3B%20background%3A%20white%3B%20border-radius%3A%2010px%3B%20box-shadow%3A%200%200%2010px%20rgba(0%2C0%2C0%2C.1)%3B%20padding%3A%2020px%3B%20%7D%0A%20%20%20%20.messages%20%7B%20height%3A%20400px%3B%20overflow-y%3A%20auto%3B%20border%3A%201px%20solid%20%23ddd%3B%20padding%3A%2010px%3B%20border-radius%3A%205px%3B%20margin-bottom%3A%2010px%3B%20%7D%0A%20%20%20%20.msg%20%7B%20margin%3A%205px%200%3B%20padding%3A%208px%3B%20border-radius%3A%206px%3B%20%7D%0A%20%20%20%20.user%20%7B%20background%3A%20%23d1e7dd%3B%20text-align%3A%20right%3B%20%7D%0A%20%20%20%20.bot%20%7B%20background%3A%20%23e2e3e5%3B%20text-align%3A%20left%3B%20%7D%0A%20%20%20%20input%20%7B%20width%3A%2080%25%3B%20padding%3A%208px%3B%20%7D%0A%20%20%20%20button%20%7B%20padding%3A%208px%2012px%3B%20%7D%0A%20%20%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object mce-object-style" width="20" height="20" alt="<style>" />
</head>
<body>
  <div class="chatbox">
    <div class="messages" id="messages"></div>
    <input type="text" id="userInput" placeholder="Type a message..." />
    <button onclick="sendMessage()">Send</button>
  </div>

  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%20%20%20%20async%20function%20sendMessage()%20%7B%0A%20%20%20%20%20%20const%20input%20%3D%20document.getElementById(%22userInput%22)%3B%0A%20%20%20%20%20%20const%20message%20%3D%20input.value.trim()%3B%0A%20%20%20%20%20%20if%20(!message)%20return%3B%0A%0A%20%20%20%20%20%20%2F%2F%20Add%20user%20message%0A%20%20%20%20%20%20addMessage(message%2C%20%22user%22)%3B%0A%20%20%20%20%20%20input.value%20%3D%20%22%22%3B%0A%0A%20%20%20%20%20%20%2F%2F%20Call%20backend%0A%20%20%20%20%20%20const%20response%20%3D%20await%20fetch(%22chatbot.php%22%2C%20%7B%0A%20%20%20%20%20%20%20%20method%3A%20%22POST%22%2C%0A%20%20%20%20%20%20%20%20headers%3A%20%7B%20%22Content-Type%22%3A%20%22application%2Fjson%22%20%7D%2C%0A%20%20%20%20%20%20%20%20body%3A%20JSON.stringify(%7B%20message%20%7D)%0A%20%20%20%20%20%20%7D)%3B%0A%0A%20%20%20%20%20%20const%20data%20%3D%20await%20response.json()%3B%0A%20%20%20%20%20%20addMessage(data.reply%2C%20%22bot%22)%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20function%20addMessage(text%2C%20type)%20%7B%0A%20%20%20%20%20%20const%20messagesDiv%20%3D%20document.getElementById(%22messages%22)%3B%0A%20%20%20%20%20%20const%20msgDiv%20%3D%20document.createElement(%22div%22)%3B%0A%20%20%20%20%20%20msgDiv.className%20%3D%20%22msg%20%22%20%2B%20type%3B%0A%20%20%20%20%20%20msgDiv.textContent%20%3D%20text%3B%0A%20%20%20%20%20%20messagesDiv.appendChild(msgDiv)%3B%0A%20%20%20%20%20%20messagesDiv.scrollTop%20%3D%20messagesDiv.scrollHeight%3B%0A%20%20%20%20%7D%0A%20%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object mce-object-script" width="20" height="20" alt="<script>" />
</body>
</html>

How It Works

  1. User types a message and clicks Send.

  2. JavaScript sends it via fetch()chatbot.php.

  3. PHP calls Gemini API and returns the AI’s response.

  4. The response is displayed in the chat window.

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"]);

Previous Article

Best Color Layouts and Themes for Student Portal UI / LMS UI [UI Color & Style Guidelines]

Next Article

Gemini chatbot : create for WordPress Plugin

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨