DEV Community

Cover image for How to Use OpenAI API with PHP (Complete Guide, 2026)
Serhii Kalyna
Serhii Kalyna

Posted on Originally published at kalyna.pro

How to Use OpenAI API with PHP (Complete Guide, 2026)

How to Use OpenAI API with PHP (Complete Guide, 2026)

PHP powers a large part of the web, but most AI tutorials focus on Python. This guide fills that gap: a complete OpenAI PHP tutorial with working code you can use in any PHP project or Laravel app.

Installation

composer require openai-php/client
Enter fullscreen mode Exit fullscreen mode

Basic Setup

$client = OpenAI::client($_ENV['OPENAI_API_KEY']);
Enter fullscreen mode Exit fullscreen mode

Chat Completions

$response = $client->chat()->create([
    'model' => 'gpt-4o',
    'messages' => [
        ['role' => 'user', 'content' => 'Explain what a PHP trait is.'],
    ],
    'max_tokens' => 256,
]);
echo $response->choices[0]->message->content;
Enter fullscreen mode Exit fullscreen mode

Key Features

  • Streaming — SSE responses with createStreamed()
  • Function calling — expose PHP functions as tools
  • Vision — pass images as URL or base64
  • Laravel — register as singleton in service provider

Cost Tips

  • Use gpt-4o-mini for simple tasks (17x cheaper than gpt-4o)
  • Set max_tokens explicitly
  • Cache responses in Redis for repeated prompts

Originally published at kalyna.pro

Top comments (0)