Integrating Google Gemini API in PHP (Generate Content & List Models)

API call to AI Model

We will learn how to connect our PHP project to Google Gemini using two practical scripts:

(1) Generate Content with our chosen model and prompt.
(2) List Models to discover the latest available Gemini models. Both scripts use cURL and a simple settings.php file to keep your API key separate.

Prerequisites


Inside AI Tools: The API Workflow (Restaurant Analogy) #aitools

1) Generate Content with a Gemini Model

Use this script to send a prompt to Gemini and print the response as HTML (safe for direct display). Update the $MODEL and $text as needed.

<?php
require 'settings.php'; // must define: $GOOGLE_API_KEY
$MODEL   = 'gemini-2.5-flash'; // <- update model
$text = " Write a short poem about the stars."; // Update your text

$url = "https://generativelanguage.googleapis.com/v1beta/models/$MODEL:generateContent";

$payload = [
  "contents" => [[
    "parts" => [["text" => $text]]
  ]]
];

$ch = curl_init($url);
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST => true,
  CURLOPT_HTTPHEADER => [
    'Content-Type: application/json',
    "x-goog-api-key: $GOOGLE_API_KEY",
  ],
  CURLOPT_POSTFIELDS => json_encode($payload),
]);
$res = curl_exec($ch);
if (curl_errno($ch)) {
  die('cURL error: ' . curl_error($ch));
}
curl_close($ch);

$data = json_decode($res, true);
if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
  echo nl2br(htmlspecialchars($data['candidates'][0]['content']['parts'][0]['text']));
} else {
  // Show full response for debugging
  echo '<pre>'.print_r($data, true).'</pre>';
}
?>

Notes

  • Model choice: gemini-2.5-flash is fast and good for short-form content. Switch to another model if needed.
  • Safety: The output is HTML-escaped via htmlspecialchars() to prevent injection.
  • Prompting: Keep your instructions explicit. You can also include URLs and formatting requirements.

2) List Available Gemini Models (with Pagination)

This helper lists all models from the ListModels endpoint. It handles pagination and prints a compact HTML table with name, display name/description, and supported generation methods.

<?php
// list-models.php
require 'settings.php'; // must define: $GOOGLE_API_KEY

/**
 * Fetch all models from Gemini ListModels endpoint (handles pagination).
 * @return array Decoded list of models (each item is an associative array)
 */
function fetchAllModels($apiKey) {
  $baseUrl = "https://generativelanguage.googleapis.com/v1beta/models";
  $models  = [];
  $pageTok = null;

  do {
    $url = $baseUrl . ($pageTok ? ("?pageToken=" . urlencode($pageTok)) : "");
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HTTPHEADER => [
        "x-goog-api-key: $apiKey",
        "Accept: application/json"
      ],
      CURLOPT_TIMEOUT => 20,
    ]);
    $res = curl_exec($ch);
    if (curl_errno($ch)) {
      throw new RuntimeException('cURL error: ' . curl_error($ch));
    }
    curl_close($ch);

    $data = json_decode($res, true);
    if (isset($data['error'])) {
      throw new RuntimeException("API error: " . ($data['error']['message'] ?? 'unknown'));
    }

    foreach (($data['models'] ?? []) as $m) {
      $models[] = $m;
    }
    $pageTok = $data['nextPageToken'] ?? null;
  } while ($pageTok);

  return $models;
}

try {
  if (empty($GOOGLE_API_KEY)) {
    throw new RuntimeException("Missing GOOGLE_API_KEY in settings.php");
  }

  $models = fetchAllModels($GOOGLE_API_KEY);

  // Simple HTML table output (safe to embed in your admin/tools page)
  echo "<h3>Available Gemini Models</h3>";
  echo "<table border='1' cellpadding='6' cellspacing='0'>";
  echo "<tr><th>Name</th><th>Description</th><th>Generation Methods</th></tr>";

  foreach ($models as $m) {
    $name   = htmlspecialchars($m['name'] ?? '');
    $desc   = htmlspecialchars($m['displayName'] ?? ($m['description'] ?? ''));
    $meth   = htmlspecialchars(implode(', ', $m['supportedGenerationMethods'] ?? []));
    echo "<tr><td><code>{$name}</code></td><td>{$desc}</td><td>{$meth}</td></tr>";
  }
  echo "</table>";

  // Optional: quick JSON dump for debugging
  // echo "<pre>" . htmlspecialchars(json_encode($models, JSON_PRETTY_PRINT)) . "</pre>";

} catch (Throwable $e) {
  http_response_code(500);
  echo "<pre>Error: " . htmlspecialchars($e->getMessage()) . "</pre>";
}
?>

settings.php (Example)

Keep your API key outside version control (use environment variables or server configs). A simple starter:

<?php
// settings.php
$GOOGLE_API_KEY = getenv('GOOGLE_API_KEY') ?: 'YOUR_API_KEY_HERE';
?>

Troubleshooting

  • 401/403: Check API key, quotas, and whether the Gemini API is enabled for your project.
  • Timeouts: Increase CURLOPT_TIMEOUT for long responses.
  • Empty content: Print the raw response (already included) to see error details from the API.
  • Model not found: Run list-models to verify the exact model name and supported generation methods.

All PHP Scripts AI Prompt Generator
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer