How to Integrate ChatGPT with PHP (Complete Guide 2026)

Published: (June 11, 2026 at 04:42 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for How to Integrate ChatGPT with PHP (Complete Guide 2026)

              [![Serhii Kalyna](https://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3919650%2F44c55224-1c4c-4ef8-9544-d23b5d5d18f2.png)](https://dev.to/kalyna_pro)
              
              
            
      

      
            

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
Enter fullscreen mode


Exit fullscreen mode
$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;
Enter fullscreen mode


Exit fullscreen mode

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'];
Enter fullscreen mode


Exit fullscreen mode

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];
Enter fullscreen mode


Exit fullscreen mode

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";
Enter fullscreen mode


Exit fullscreen mode

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 */ }
Enter fullscreen mode


Exit fullscreen mode

Originally published at kalyna.pro

0 views
Back to Blog

Related posts

Read more »

The spec is in the wrong place

My day job is at a large tech company. Hundreds of engineering teams, and every one of them is somewhere different on AI adoption. Some are still treating codin...

The Heuristics Say Don't

A culture that only records its disasters ends up with a biased archive. Wars documented, plagues chronicled, collapses catalogued. The quiet decades go unwritt...