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
Basic Setup
$client = OpenAI::client($_ENV['OPENAI_API_KEY']);
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;
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-minifor simple tasks (17x cheaper than gpt-4o) - Set
max_tokensexplicitly - Cache responses in Redis for repeated prompts
Originally published at kalyna.pro
Top comments (0)