Skip to main content

Basic Chat

<?php

$apiKey = 'sk-xxx';
$baseUrl = 'https://crazyrouter.com/v1';

$data = [
    'model' => 'gpt-4o',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, write a bubble sort in PHP']
    ]
];

$ch = curl_init($baseUrl . '/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_RETURNTRANSFER => true,
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
echo $result['choices'][0]['message']['content'];

Image Editing

<?php

$apiKey = 'sk-xxx';
$baseUrl = 'https://crazyrouter.com/v1';

// Edit image with GPT-Image-1
$ch = curl_init($baseUrl . '/images/edits');

$postFields = [
    'model' => 'gpt-image-1',
    'image' => new CURLFile('original.png', 'image/png'),
    'prompt' => 'Change the background to a starry sky',
];

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS => $postFields,
    CURLOPT_RETURNTRANSFER => true,
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

// Save base64 image
$imageData = base64_decode($result['data'][0]['b64_json']);
file_put_contents('edited.png', $imageData);
echo "Image saved to edited.png\n";

Streaming Output

<?php

$apiKey = 'sk-xxx';
$baseUrl = 'https://crazyrouter.com/v1';

$data = [
    'model' => 'gpt-4o',
    'messages' => [['role' => 'user', 'content' => 'Tell me a joke']],
    'stream' => true,
];

$ch = curl_init($baseUrl . '/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_WRITEFUNCTION => function ($ch, $data) {
        $lines = explode("\n", $data);
        foreach ($lines as $line) {
            if (str_starts_with($line, 'data: ') && $line !== 'data: [DONE]') {
                $json = json_decode(substr($line, 6), true);
                $content = $json['choices'][0]['delta']['content'] ?? '';
                echo $content;
            }
        }
        return strlen($data);
    },
]);

curl_exec($ch);
curl_close($ch);
echo "\n";
For PHP 7.4+, the openai-php/client package is recommended for a friendlier SDK experience. Install with: composer require openai-php/client