ChatGPT를 PHP와 통합하는 방법 (전체 가이드 2026)

작성자

카테고리:

← 피드로
DEV Community · Serhii Kalyna · 2026-06-11 개발(SW)
Cover image for How to Integrate ChatGPT with PHP (Complete Guide 2026)

Serhii Kalyna

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]) . "nn"; ob_flush(); flush(); }
}
echo "data: [DONE]nn";

Enter fullscreen mode Exit fullscreen mode

Error Handling

use OpenAIExceptionsErrorException;
use OpenAIExceptionsTransporterException;
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

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다