Create a chatbot in PHP using the Gemini API (from Google AI)

chatbot_gemani_ipdata_code

Requirements

  1. PHP 7.4+

  2. cURL enabled in PHP

  3. 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
}
?>
Next Article

PDF in WordPress using FPDF : Custom PDF Generator

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 ✨