Priya already has a marks list and a fee register at Shree Vidya Tuition Centre. What she still writes by hand is the short message to a parent: “Ananya Sharma has a balance of ₹1,200 for November tuition. Kindly pay at the office this week.” That sentence is a good first job for an AI API. PHP will collect the facts; the model will only turn them into polite prose.
This lesson shows how to call a chat-completions endpoint that follows the OpenAI-compatible JSON shape, using PHP and cURL. The same request works with many providers that expose /v1/chat/completions. You will read the API key from an environment variable, send JSON, handle failures, and pick the message text out of the response. We will not hardcode a key, and we will not let the model invent the rupee amount — your PHP already knows the balance.
Key takeaways
- An OpenAI-compatible chat call is a POST of JSON to
/v1/chat/completions. - The API key belongs in an environment variable such as
AI_API_KEY, never in the source file or in HTML. - Handle transport errors, bad JSON, non-2xx status codes, and a missing
choices[0].message.contentseparately. - Put official amounts and names into the prompt from your own data.
- Escape the model’s text with
htmlspecialcharsbefore you display it.
What you are calling
A typical request is an HTTP POST to {base url}/v1/chat/completions. The body is JSON:
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts."
},
{
"role": "user",
"content": "Write a 2-sentence reminder that Ananya Sharma has a balance of ₹1,200 for November tuition."
}
],
"max_tokens": 200
}
The system message sets the tone. The user message holds the task and the facts. Put the rupee amount in that user text yourself. If you only say “remind them about the pending fee,” the model may guess a number, which is not acceptable for money.
A successful response includes a choices array. The text you want is usually here:
choices[0].message.content
Everything else (id, usage, finish reason) is useful later for logging and cost, but the first lesson only needs the content string.
Keep the API key out of your code
The request is authorized with a header:
Authorization: Bearer YOUR_KEY_HERE
The key is a secret. It is not a PHP variable you type into the file and upload to the server. Anyone who can read that file, a backup, or a git history could bill your account. Read it from the environment instead.
<?php
declare(strict_types=1);
function apiKeyFromEnv(string $name = 'AI_API_KEY'): string
{
$key = getenv($name);
if ($key === false || $key === '') {
throw new RuntimeException(
"Missing API key. Set the $name environment variable. Do not hardcode the key in PHP files."
);
}
return $key;
}
On your laptop you can export the variable in the shell before you run the script:
export AI_API_KEY="paste-the-key-here"
php reminder.php
On a server, set it in the hosting panel, in a systemd unit, or in a file outside the web root that your process manager loads. Never print the key, never echo it into HTML, and never send it to the browser. This lesson’s tests checked that an empty key throws and a present key is returned, and never printed the value.
You can also read the base URL from the environment, with a sensible default, so the same script can point at OpenAI, a compatible proxy, or a local mock while you practise:
$baseUrl = getenv('AI_API_BASE') ?: 'https://api.openai.com';
$model = getenv('AI_MODEL') ?: 'gpt-4o-mini';
Build the JSON and send it with cURL
function buildChatRequest(string $model, array $messages, ?int $maxTokens = 200): array
{
$body = [
'model' => $model,
'messages' => $messages,
];
if ($maxTokens !== null) {
$body['max_tokens'] = $maxTokens;
}
return $body;
}
function callChatCompletions(
string $baseUrl,
string $apiKey,
array $payload,
int $timeoutSeconds = 20
): array {
$url = rtrim($baseUrl, '/') . '/v1/chat/completions';
$json = json_encode($payload, JSON_UNESCAPED_UNICODE);
if ($json === false) {
throw new RuntimeException('Could not encode the request as JSON.');
}
$ch = curl_init($url);
if ($ch === false) {
throw new RuntimeException('Could not start cURL.');
}
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
],
CURLOPT_POSTFIELDS => $json,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeoutSeconds,
]);
$responseBody = curl_exec($ch);
if ($responseBody === false) {
$err = curl_error($ch);
curl_close($ch);
throw new RuntimeException('cURL error: ' . $err);
}
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decoded = json_decode($responseBody, true);
if (!is_array($decoded)) {
throw new RuntimeException('The API did not return valid JSON. HTTP ' . $status);
}
if ($status < 200 || $status >= 300) {
$message = $decoded['error']['message'] ?? ('HTTP ' . $status);
throw new RuntimeException('API error: ' . $message);
}
$text = $decoded['choices'][0]['message']['content'] ?? null;
if (!is_string($text) || $text === '') {
throw new RuntimeException('The API response had no message content.');
}
return [
'status' => $status,
'content' => $text,
'raw' => $decoded,
];
}
A few choices in that function are deliberate. CURLOPT_RETURNTRANSFER gives you the body as a string so you can decode it, instead of printing it straight out. CURLOPT_TIMEOUT stops a hung call from blocking a web page forever; twenty seconds is a starting point, not a rule. JSON_UNESCAPED_UNICODE keeps the rupee sign readable in logs of the request body.
Error handling comes in layers, and you should keep them separate:
- cURL itself failed (DNS, timeout, TLS):
curl_execreturnsfalse. The API never produced a body you can trust. - The server answered, but not with JSON:
json_decodewill not return an array. Log the HTTP status and a short snippet of the body, not the key. - JSON arrived with a 4xx or 5xx status: many providers put a human message in
error.message(for example an invalid key). Surface that to yourself, not a raw dump, on a public page. - A 200 response with an empty
choices[0].message.content: treat it as a failure so you do not email a parent a blank note.
Put it together for a fee reminder
$apiKey = apiKeyFromEnv();
$baseUrl = getenv('AI_API_BASE') ?: 'https://api.openai.com';
$student = 'Ananya Sharma';
$balance = 1200; // rupees; this value comes from your database, not from the model
$month = 'November';
$payload = buildChatRequest(
getenv('AI_MODEL') ?: 'gpt-4o-mini',
[
[
'role' => 'system',
'content' => 'You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts or dates.',
],
[
'role' => 'user',
'content' => sprintf(
'Write a 2-sentence reminder that %s has a balance of ₹%s for %s tuition.',
$student,
number_format($balance),
$month
),
],
]
);
try {
$result = callChatCompletions($baseUrl, $apiKey, $payload);
echo htmlspecialchars($result['content'], ENT_QUOTES, 'UTF-8');
} catch (RuntimeException $e) {
http_response_code(502);
echo 'Could not write the reminder just now. Please try again or send it by hand.';
error_log('AI reminder failed: ' . $e->getMessage());
}
Two habits from the earlier tracks still apply. The rupee figure is formatted in PHP with number_format, then placed in the prompt. And whatever the model returns is passed through htmlspecialchars before it goes into a web page. A model is not a trusted source, even when you sent it the facts.
Try this
First run the script without setting AI_API_KEY. You should get the missing-key error, not a request to the network. Then set a fake key and point AI_API_BASE at a local mock, or at a real compatible endpoint if you already have an account. Change the user message so the balance is ₹2,450 and the student is Rahul Iyer. Confirm that the reply mentions ₹2,450 and does not invent a different amount. If it changes the figure, tighten the system message and, in a later lesson, add a check that the output still contains the amount you supplied.
How this was tested
On PHP 8.4, the request builder produced valid JSON, an empty AI_API_KEY raised the missing-key exception, and a sample success body parsed to the reminder text. The cURL function was then pointed at a local mock of POST /v1/chat/completions: a matching Bearer token returned HTTP 200 and a ₹1,200 message; a wrong token returned HTTP 401 and the function threw API error: Invalid API key. No paid API was called here, so run one live call against your own provider before you rely on it.
What you learned
- An OpenAI-compatible chat call is a POST of JSON to
/v1/chat/completions, withmodeland amessageslist. - The API key belongs in an environment variable such as
AI_API_KEY, never in the source file or in HTML. - PHP’s cURL extension can send the request, apply a timeout, and return the body for
json_decode. - Handle transport errors, bad JSON, non-2xx status codes, and a missing
choices[0].message.contentas separate failures. - Put official amounts (₹1,200, a month, a student name) into the prompt from your own data, and escape the model’s text before you display it.
Quick quiz
-
1. Where should the API key be stored?
- A) In a PHP string at the top of the file, so it is easy to change
- B) In an environment variable, read with
getenv() - C) In a hidden HTML field
Show answer
B. A key in the source (or in HTML) can leak through backups, git history, or the browser. Use
AI_API_KEYor a similar env var. -
2. After a successful JSON response, where is the assistant text usually found?
- A)
choices[0].message.content - B)
error.message - C) The HTTP status line
Show answer
A. Treat a missing or empty content string as a failure so you do not show a blank reminder.
- A)
-
3.
curl_execreturnsfalse. What should you do first?- A) Decode the body as JSON anyway
- B) Treat it as a transport failure and read
curl_error— there is no trustworthy body - C) Retry with the key hardcoded
Show answer
B. A false return means cURL itself failed (timeout, DNS, TLS). That is a different problem from an HTTP 401 with a JSON error message.
-
4. Who should decide that Ananya’s balance is ₹1,200?
- A) The model, if you say “whatever is outstanding”
- B) Your PHP (or database), which then places ₹1,200 in the user message
- C) A default in the system prompt
Show answer
B. Money and names are facts you already have. The model’s job is the wording.
Next lesson
Next in the PHP + AI track, you will ask the model for structured JSON — for example {"greeting": "...", "body": "..."} — and validate that JSON in PHP before you use it. After that comes a short lesson on keys, quotas, and cost, so a loop in a script cannot run up a surprise bill. The first AI project on this site will reuse today’s function to draft a parent fee reminder from a real balance in the database.