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.
settings.php
with $GOOGLE_API_KEY
defined.
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>';
}
?>
gemini-2.5-flash
is fast and good for short-form content. Switch to another model if needed.htmlspecialchars()
to prevent injection.
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>";
}
?>
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';
?>
CURLOPT_TIMEOUT
for long responses.error
details from the API.Author
🎥 Join me live on YouTubePassionate 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.