How to Integrate ChatGPT with PHP (Complete Guide 2026)
This guide covers every approach: official PHP SDK, raw cURL, conversation history, streaming SSE, and a working chat form.
Option A: Official SDK
composer require openai-php/client
$client = OpenAI::client(getenv('OPENAI_API_KEY'));
$response = $client->chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [['role' => 'user', 'content' => 'Hello!']],
]);
echo $response->choices[0]->message->content;
Option B: Raw cURL
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(['model' => 'gpt-4o-mini', 'messages' => [['role' => 'user', 'content' => $msg]]]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Authorization: Bearer ' . $key],
]);
$data = json_decode(curl_exec($ch), true);
echo $data['choices'][0]['message']['content'];
Conversation History
session_start();
$_SESSION['messages'][] = ['role' => 'user', 'content' => $input];
$response = $client->chat()->create(['model' => 'gpt-4o-mini', 'messages' => $_SESSION['messages']]);
$reply = $response->choices[0]->message->content;
$_SESSION['messages'][] = ['role' => 'assistant', 'content' => $reply];
Streaming SSE
header('Content-Type: text/event-stream');
$stream = $client->chat()->createStreamed(['model' => 'gpt-4o-mini', 'messages' => $messages]);
foreach ($stream as $r) {
$delta = $r->choices[0]->delta->content;
if ($delta) { echo "data: " . json_encode(['chunk' => $delta]) . "\n\n"; ob_flush(); flush(); }
}
echo "data: [DONE]\n\n";
Error Handling
use OpenAI\Exceptions\ErrorException;
use OpenAI\Exceptions\TransporterException;
try {
$reply = $client->chat()->create([...])->choices[0]->message->content;
} catch (ErrorException $e) { /* API error */ }
catch (TransporterException $e) { /* Network error */ }
Originally published at kalyna.pro