Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A PHP image-generation SDK is a server-side client for an image provider. Your application stores credentials securely, sends a prompt and output options, receives a URL or encoded image data, and then saves or serves the result. The exact methods and model names vary by provider and package, so verify the current Composer metadata and API documentation before deploying.

This guide uses OpenAI as a concrete example with the openai-php/client package. Use the Image API for a single generation or edit, and choose the Responses API when image creation belongs inside a conversation or a multi-step editing workflow.

Choose the API workflow before writing PHP

Image API: one-shot generation and editing

The Image API is the straightforward choice when a request should produce an image (or edit supplied image input) without conversational state. Your PHP endpoint accepts application input, builds one request, and handles the returned image representation.

Responses API: conversational and iterative work

The Responses API can invoke image generation during a conversation. It is a better fit when users refine an image over several turns, when earlier instructions must remain in context, or when your application combines image generation with other response steps. That orchestration is more involved than a direct image call.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Requirement Better starting point
One prompt produces one asset Image API
Generate or edit in several conversational turns Responses API
Direct image input and simple output handling Image API
Contextual workflows, conversation state, or file-based inputs Responses API

Model identifiers, parameters, and response fields can change. Treat the examples below as a pattern to verify against the current provider and package versions, not as a promise that every historical model remains available.

Install a PHP client

The community PHP client used here is openai-php/client. Install the version currently documented by its repository and confirm its supported PHP version and extensions before running production code:

composer require openai-php/client

Keep the API key on the server. Load it from your process environment or your hosting platform’s secret store; do not place it in JavaScript, HTML, a mobile bundle, or a publicly committed configuration file.

export OPENAI_API_KEY='replace-with-your-key'

The client factory and method signatures can differ between major releases. Check the installed package’s README if a factory method shown here is not recognized.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate an image with PHP

The following complete example creates a square image, requests a URL response, downloads it, and writes it to a local file. It assumes the package version exposes the documented images()->create() resource.

<?php
require __DIR__ . '/vendor/autoload.php';

use OpenAIClient;

$apiKey = getenv('OPENAI_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('OPENAI_API_KEY is not configured');
}

$client = OpenAI::client($apiKey);

$result = $client->images()->create([
    'model' => 'gpt-image-1',
    'prompt' => 'A clean editorial illustration of a PHP developer building an image pipeline, blue and amber accents, no text',
    'size' => '1024x1024',
    'quality' => 'medium',
    'output_format' => 'webp',
]);

$item = $result->data[0] ?? null;
if (!$item) {
    throw new RuntimeException('The API returned no image item');
}

$url = $item->url ?? null;
if (!$url) {
    throw new RuntimeException('This response did not contain an image URL');
}

$imageBytes = file_get_contents($url);
if ($imageBytes === false) {
    throw new RuntimeException('Could not download the generated image');
}

if (!is_dir(__DIR__ . '/generated')) {
    mkdir(__DIR__ . '/generated', 0750, true);
}
file_put_contents(__DIR__ . '/generated/illustration.webp', $imageBytes);
echo "Saved generated/illustration.webpn";

Use a model identifier that the provider currently documents. Some responses expose a temporary URL; others return base64 data. Do not assume a URL is permanent. Download the bytes promptly, validate the content type and size, and move the file into durable object storage if the asset must persist.

Handle base64 responses

If you request or receive encoded image data, decode it on the server and check for failure before writing. The exact option name is package- and model-dependent; the PHP client README demonstrates response data items with URL and base64 fields.

$result = $client->images()->create([
    'model' => 'gpt-image-1',
    'prompt' => 'A simple isometric server rack, neutral background',
    'size' => '1024x1024',
    'response_format' => 'b64_json',
]);

$item = $result->data[0] ?? null;
$encoded = $item->b64_json ?? null;
if (!$encoded) {
    throw new RuntimeException('No base64 image was returned');
}

$bytes = base64_decode($encoded, true);
if ($bytes === false) {
    throw new RuntimeException('Invalid base64 image data');
}
file_put_contents(__DIR__ . '/generated/rack.png', $bytes);

Use the representation your selected model supports. A URL field and a base64 field are not interchangeable, and a field can be absent when the request’s response format is unsupported.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set size, quality, format, and background deliberately

Dimensions and aspect ratio

Choose square, landscape, or portrait dimensions based on where the asset will appear. For documented models that allow custom dimensions, width and height must be multiples of 16, the aspect ratio must be between 1:3 and 3:1, neither edge may exceed 3,840 pixels, and total pixels must be between 655,360 and 8,294,400. Verify these limits immediately before release because model support is subject to change.

Quality

Use a lower quality setting for previews and iteration, then compare a higher quality setting for final assets. Higher quality can increase processing time and usage cost; do not use it for every draft automatically.

Format and compression

PNG is useful when lossless output or transparency matters. JPEG is broadly compatible and usually smaller for photographic images. WebP can reduce file size while retaining modern browser support. If you need transparent output with the documented GPT Image models, select PNG or WebP rather than JPEG. Where supported, set compression explicitly and measure the resulting size against your storage and delivery requirements.

Background

Use a transparent background for compositing, or an opaque background for a ready-to-publish card. A transparent request only helps if the selected format and model support it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate multiple images and stream where appropriate

If your provider and package support a count parameter, request several variations in one operation and iterate over every returned data item:

$result = $client->images()->create([
    'model' => 'gpt-image-1',
    'prompt' => 'Four distinct geometric app icons, consistent style',
    'n' => 4,
    'size' => '1024x1024',
]);

foreach ($result->data as $index => $item) {
    // Handle $item->url or $item->b64_json according to the response.
}

A streamed creation method is also shown by the PHP client README. Streaming can improve perceived responsiveness for a long-running request, but it does not remove the need to persist the final image and inspect errors. Confirm the stream method and event shape in your installed version before using it.

Editing and multi-turn image workflows

Editing with the Image API

Use the Image API’s edit operation when your application has an input image and a direct instruction such as removing an object, changing a background, or applying a visual style. Supply the image and any mask or additional fields required by the current endpoint. Validate file type, dimensions, and upload limits before forwarding user files.

Iterating with the Responses API

For a user interface that says “make the jacket green,” then “use a wider crop,” preserve the conversation or the provider’s returned context and send the next instruction through the Responses API’s image-generation tool. Store the resulting asset reference in your own database; do not rely on transient provider URLs as permanent records.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Production response handling

  • Validate that a response contains exactly the fields your selected representation requires.
  • Check HTTP status codes and catch the SDK’s documented exception type for your installed package.
  • Log the provider request ID, timestamp, model, and your internal job ID, but never log the API key or sensitive prompt content by default.
  • Use bounded timeouts, retry only transient rate-limit or server failures, and apply exponential backoff with a maximum attempt count.
  • Write files atomically, scan or validate downloaded content, and enforce an application-level maximum file size.
  • Keep user-facing jobs asynchronous when generation may exceed a normal web-request timeout. Return a job identifier and let a worker save the final asset.

Troubleshooting common failures

Authentication or missing-key errors

Confirm the environment variable is present in the PHP-FPM, queue-worker, or container process that actually runs the request. A key exported in an interactive shell is not automatically available to a web worker. Rotate exposed keys and remove them from logs and source control.

Invalid model or parameter

Model names and accepted options are provider-specific. Check the current model documentation and package types, then remove unsupported fields one at a time. A parameter copied from another image provider will not necessarily be accepted.

Invalid dimensions or format

Use a documented preset first. If using custom dimensions, verify the multiple-of-16, aspect-ratio, edge, and pixel-count constraints. For transparency, switch from JPEG to PNG or WebP.

Rate limits, quota, or timeouts

Inspect the HTTP status and exception details, record the request ID, and retry only when the error is transient. Queue work rather than holding a browser request open, and show a useful pending state to the user.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Successful response but no usable file

Inspect whether the item contains url or b64_json. Download URL data immediately, use strict base64 decoding for encoded data, and confirm the written file’s MIME type and byte length before publishing it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your PHP application also needs screenshots of web pages—for documentation, previews, or regression artifacts—you can call ScreenshotNeo instead of maintaining browser automation. It is a separate website screenshot API and MCP server, not an image-generation model.

One GET request returns a PNG, JPEG, WebP, or PDF. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo documentation for all options. A PHP request can be made with cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
$ch = curl_init('https://api.screenshotneo.com/v1/shot?' . http_build_query([
    'access_key' => getenv('SCREENSHOTNEO_API_KEY'),
    'url' => 'https://stripe.com',
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 90);
$bytes = curl_exec($ch);
if ($bytes === false) {
    throw new RuntimeException(curl_error($ch));
}
curl_close($ch);
file_put_contents(__DIR__ . '/stripe.webp', $bytes);

Plans include 1,000 screenshots a month free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

cURL, Python, and Node.js equivalents

These requests use the same ScreenshotNeo endpoint and can be useful from a worker or build pipeline:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());

Frequently Asked Questions

Is an SDK required to generate images from PHP?

No. An SDK is a convenience client over the provider’s HTTP API. You can send authenticated HTTP requests directly, but an SDK usually simplifies serialization, resource methods, and exception handling.

Where should generated images be stored?

Download URL responses promptly or decode base64 responses, then store the bytes in durable application storage such as object storage. Save metadata—model, prompt policy, format, dimensions, and provider request ID—alongside your internal asset record.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can browser JavaScript call the image provider directly?

Do not expose a server API key in browser code. Send the user’s request to your server, validate it there, and have the server call the provider.

The Bottom Line

Pick the provider workflow first: use the Image API for a direct generation or edit and the Responses API for conversational iteration. In PHP, keep credentials server-side, set output options intentionally, support both URL and base64 responses, and log request IDs when failures occur.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.