Claude API PHP Integration Tutorial & Guide
If you're building a PHP application and want to add Claude for chat, content generation, or document analysis, you need to know how to authenticate, send requests, parse responses, and handle errors correctly from PHP specifically — since there's no official Claude PHP SDK maintained by Anthropic. This guide walks through a working integration using plain cURL and composer-friendly patterns, so you can drop Claude into a Laravel, Symfony, or vanilla PHP project without guessing at syntax.
We'll cover authentication, a basic message request, streaming responses, error handling, and a note on why many PHP teams route requests through a gateway like SubToAPI instead of managing raw API keys and retry logic themselves.
Prerequisites
Before writing code, you need:
- PHP 7.4+ (8.1+ recommended) with the
curlandjsonextensions enabled - An API key — either an Anthropic key, or an application key from a service like SubToAPI
composerinstalled if you want to use an HTTP client library instead of raw cURL
No official PHP SDK exists for Claude, which means most PHP developers either write their own thin wrapper (shown below) or use Guzzle for cleaner HTTP handling.
Step 1: Store your API key safely
Never hardcode the key. Use environment variables via .env and a loader like vlucas/phpdotenv:
composer require vlucas/phpdotenv
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$apiKey = $_ENV['CLAUDE_API_KEY'];
Step 2: Send a basic message request with cURL
Here's a minimal PHP function that sends a message to Claude and returns the decoded response:
function sendClaudeMessage(string $apiKey, string $prompt): array
{
$ch = curl_init('https://api.anthropic.com/v1/messages');
$payload = json_encode([
'model' => 'claude-3-5-sonnet-20241022',
'max_tokens' => 1024,
'messages' => [
['role' => 'user', 'content' => $prompt],
],
]);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-api-key: ' . $apiKey,
'anthropic-version: 2023-06-01',
],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new RuntimeException("Claude API error ($httpCode): $response");
}
return json_decode($response, true);
}
Usage:
$result = sendClaudeMessage($apiKey, 'Summarize this invoice in two sentences.');
echo $result['content'][0]['text'];
This is enough for most backend tasks: form processing, content generation, classification, summarization.
Step 3: Using Guzzle instead of raw cURL
If your project already uses Guzzle (common in Laravel/Symfony apps), it's cleaner for timeouts, retries, and testing:
composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
$client = new Client(['base_uri' => 'https://api.anthropic.com']);
$response = $client->post('/v1/messages', [
'headers' => [
'x-api-key' => $apiKey,
'anthropic-version' => '2023-06-01',
'Content-Type' => 'application/json',
],
'json' => [
'model' => 'claude-3-5-sonnet-20241022',
'max_tokens' => 1024,
'messages' => [
['role' => 'user', 'content' => 'Write a product description for a desk lamp.'],
],
],
]);
$data = json_decode($response->getBody(), true);
echo $data['content'][0]['text'];
Guzzle gives you connection timeouts, retry middleware, and async requests, which matter once you're calling Claude from a web request handler and don't want a slow upstream call to hang your app.
Step 4: Handling streaming responses in PHP
Streaming matters for chat UIs where you want tokens to appear as they're generated rather than waiting for the full response. PHP can handle Server-Sent Events (SSE) with cURL's CURLOPT_WRITEFUNCTION:
$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
'model' => 'claude-3-5-sonnet-20241022',
'max_tokens' => 512,
'stream' => true,
'messages' => [['role' => 'user', 'content' => 'Tell me a short story.']],
]),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-api-key: ' . $apiKey,
'anthropic-version: 2023-06-01',
],
CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {
foreach (explode("\n", $chunk) as $line) {
if (str_starts_with($line, 'data: ')) {
$json = json_decode(substr($line, 6), true);
if (isset($json['delta']['text'])) {
echo $json['delta']['text'];
flush();
}
}
}
return strlen($chunk);
},
]);
curl_exec($ch);
curl_close($ch);
This works in a CLI script or behind a web server with ob_flush() added if output buffering is enabled. Streaming from PHP-FPM through nginx requires disabling buffering on that route (fastcgi_buffering off).
Step 5: Error handling and retries
Production PHP integrations need to handle rate limits (429), overload errors (529), and transient network failures. A simple retry wrapper with exponential backoff:
function sendWithRetry(callable $fn, int $maxAttempts = 3)
{
$attempt = 0;
while (true) {
try {
return $fn();
} catch (RuntimeException $e) {
$attempt++;
if ($attempt >= $maxAttempts) {
throw $e;
}
sleep(2 ** $attempt);
}
}
}
A simpler path: SubToAPI as your PHP backend
Managing raw API keys, retry logic, streaming buffers, and per-feature usage tracking adds real maintenance overhead to a PHP app, especially on a small team. SubToAPI turns your existing Claude access into a stable HTTPS endpoint with its own application keys (sub_live_...), so your PHP code stays exactly the same shape as above — just point requests at https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY instead of juggling provider-specific headers.
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.subtoapi.app/v1/messages',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $_ENV['SUBTOAPI_KEY'],
],
]);
You get streaming, tool use, and usage metadata out of the box, plus a dashboard for team seats instead of sharing one raw key across developers. The quickstart covers signup to first request in a few minutes, and /docs/messages and /docs/streaming mirror the patterns shown above. Plans start at €9/month for solo developers, scaling to team and multi-seat tiers — see /pricing for details, or sign up for a free trial.
questions
Is there an official Claude PHP SDK? No. Anthropic maintains official SDKs for Python and TypeScript/JavaScript. PHP developers use cURL directly or an HTTP client like Guzzle, as shown in this guide.
Can I stream Claude responses in a PHP web app? Yes, using CURLOPT_WRITEFUNCTION to process Server-Sent Events as they arrive. On nginx/PHP-FPM you need fastcgi_buffering off on that route for chunks to reach the browser in real time.
What's the fastest way to add Claude to an existing PHP app without managing API infrastructure? Point your existing HTTP client code at an API gateway like SubToAPI instead of Anthropic's endpoint directly — you keep the same request/response shape but get streaming, usage tracking, and team key management included.