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.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

A PHP image-generation SDK is a server-side client for a specific provider’s API, not a provider-independent image engine. Choose the provider and workflow first, install its PHP package, keep credentials on the server, submit a prompt and output settings, then handle the returned URL or image data in your application. This guide uses OpenAI’s openai-php/client as a documented example; verify the package’s current Composer metadata and model documentation before using it, since package requirements and supported model identifiers can change.

Choose the API workflow before writing PHP

OpenAI offers two useful ways to include image generation. The Image API is suited to a direct generation or editing request. The Responses API can generate images in a conversation, making it a better fit for multi-turn work in which a user refines an image through follow-up instructions. The right choice depends on how much conversational context and orchestration your application needs, not on PHP itself. OpenAI’s image-generation guide describes the available workflows.

Workflow Use it when What your application manages
Image API You need a straightforward generation or image-editing operation. One request and the resulting image response.
Responses API Image generation belongs in a conversation or a sequence of edits. Conversation context, follow-up turns, and the image-generation step.

The Image API accepts image-generation and editing tasks. Responses API workflows support image generation within a conversation and multi-turn editing. The Responses API also supports contextual workflows that can use file IDs, while the Image API is a more direct image task. Confirm current request shapes and model availability in the provider documentation before committing to either integration.

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

Install the PHP client and configure credentials

The example package is openai-php/client. Its README documents installation through Composer and demonstrates image resource methods. Check the current repository README and Composer metadata for the exact command, PHP version, extensions, and method signatures supported by the version you install. Those details are package-version-specific.

composer require openai-php/client

Store the API key in server-side configuration or an environment variable. Do not put it in JavaScript, HTML, mobile application code, or a repository. For example, define OPENAI_API_KEY in the environment used by your PHP process and load it through your deployment configuration. Ensure the value is not exposed in error pages or logs.

Construct the SDK client in server-side PHP using the package’s documented client factory and the environment value. The README demonstrates the package’s client and image resource patterns; exact factory and exception details can vary by installed version, so follow that version’s documentation.

<?php

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

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

// Create the client using the factory documented by your installed
// openai-php/client version, with $apiKey as the credential.

The snippet intentionally leaves client construction to the installed package’s current documented factory rather than assuming a method signature that may change. Do not copy a client-construction example from an older package release without checking the version in your lock file.

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

Generate an image with the Image API

The PHP client README demonstrates calling $client->images()->create([...]) with a model, prompt, count, size, and response format. Once you have created $client using the factory for your installed package, a request follows this shape:

$result = $client->images()->create([
    'model' => 'gpt-image-1',
    'prompt' => 'A small reading nook beside a rain-streaked window, warm lamp light, editorial illustration',
    'n' => 1,
    'size' => '1024x1024',
]);

Treat the model identifier and accepted parameters as version-sensitive: check the provider’s current image guide and the installed client’s README before deploying. The PHP method makes the HTTP API easier to call, but it does not remove the need to choose model-supported values or handle API failures.

For multi-turn generation or editing, use the Responses API flow documented by OpenAI and the corresponding methods available in your installed PHP client version. Carry forward the conversation or response context the API requires, and pass an edit instruction as a new turn. Do not assume the Image API’s single-request response pattern is interchangeable with a conversational response.

Choose dimensions, quality, format, and background

Output settings affect how useful the asset is and can affect latency and cost. Decide these based on the destination rather than relying on defaults:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Size and aspect ratio: Choose a square, landscape, or portrait shape that matches the placement. OpenAI’s guide lists common dimensions and permits custom width and height subject to documented constraints.
  • Quality: Use lower quality for quick drafts or iteration and compare higher quality for final assets. The appropriate setting depends on the image and intended use; do not assume one quality choice is best for every prompt.
  • Format and compression: Select the file type and compression for the receiving application and its storage or delivery needs. The guide documents format and compression options for supported models.
  • Background: If transparency is required, use PNG or WebP for the documented GPT Image models and select the applicable background option. Confirm current model support before relying on transparency.

For custom dimensions, the guide documents constraints for the models it covers: 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 pixel count must be between 655,360 and 8,294,400. These are API constraints, not universal image-format rules. Model support and constraints can change, so verify them in the current official guide before building validation around them.

Read and store the response safely

Image responses can provide a URL or base64-encoded image data, depending on the endpoint, model, and response format. The PHP client README demonstrates reading returned data items and URL or base64 fields; the Images API reference documents response fields. Inspect the actual response shape for the request you made rather than assuming every model returns the same representation.

If the response contains a URL, fetch or otherwise process it according to your storage policy, and do not assume the URL is a permanent asset URL. If it contains base64 data, decode it before writing a file. In either case, validate that the response includes image content before treating the request as successful.

// Inspect the response structure supported by your installed client version.
// A response data item may provide a URL or base64 image payload.
foreach ($result->data as $image) {
    if (isset($image->url)) {
        // Retrieve and store the image using your application's
        // HTTP and storage layer; apply size and content validation.
    } elseif (isset($image->b64_json)) {
        $bytes = base64_decode($image->b64_json, true);
        if ($bytes === false) {
            throw new RuntimeException('Image payload was not valid base64.');
        }
        // Write $bytes using a safe, application-controlled filename
        // and your chosen storage backend.
    } else {
        throw new RuntimeException('No supported image field in response.');
    }
}

The SDK’s returned object may expose properties differently across package versions. Confirm whether your installed version returns objects, arrays, or another response type before adapting this example. For production, use generated or application-controlled filenames, enforce size limits, and keep private user-generated assets behind the authorization rules your application requires.

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

Handle errors, retries, and operational visibility

OpenAI advises checking the HTTP status or SDK exception type, logging the request ID, and consulting its error guidance for authentication, quota, rate-limit, and server failures. The exact PHP exception classes depend on the package version. Catch the documented exceptions for your installed client and retain safe diagnostic context; never log API keys or sensitive prompt contents unless your data policy explicitly allows it.

  • Authentication failure: Check that the server process received the intended key, that it is valid for the provider account, and that configuration did not include stray whitespace.
  • Quota or billing error: Inspect account and project limits rather than retrying the same request repeatedly.
  • Rate limit: Apply bounded backoff and respect any retry guidance in the response. Avoid an unbounded retry loop.
  • Server or transient network failure: Use a limited retry policy where safe, record the request ID when available, and expose a useful application error instead of returning raw provider details to the browser.
  • Invalid image settings: Validate the selected model, dimensions, quality, format, and background against current model documentation.

For errors, request identifiers, and recommended handling, see OpenAI’s error-codes guide and its image-generation guide. Measure your own request duration and failure rate in the application; no universal generation latency or cost figure applies to every model, prompt, and setting.

Use the SDK’s streaming method where appropriate

The PHP client README also shows a streamed image-creation method. Streaming can be useful when an application wants incremental output rather than waiting for a completed result, but it changes how the caller consumes the response. Confirm the stream event format and supported models for your package and API version, then ensure your PHP runtime and web-server setup can keep the response open for the required duration. A streamed method is not automatically faster, and it does not replace error handling or durable storage.

Common PHP integration problems

Composer resolves an incompatible package or PHP requirement

Read the installed package’s Composer constraints and your project’s PHP version before deployment. Use a compatible release rather than assuming the newest package supports every PHP runtime. Commit the lock file so environments install the same resolved dependency versions.

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

The key works locally but is missing in production

Verify the environment variable in the PHP-FPM, worker, or container process that actually makes the request. Shell variables set for an interactive login are not necessarily inherited by web workers. Keep the key server-side and rotate it if it has been exposed.

The response has no URL

The request may have selected a representation that returns base64 image data, or the selected model may expose a different shape. Inspect the response using safe development logging and implement the branch appropriate to the response format rather than assuming a URL.

The request is rejected for custom dimensions

Check the documented multiple-of-16 rule, aspect-ratio range, edge limit, and total pixel range for the specific models covered by the current guide. Also confirm that the chosen model accepts custom dimensions at all.

The browser cannot access the generated image

Do not assume a server-side image URL is suitable for direct browser delivery or permanent hosting. Retrieve and store the file through your application’s backend, then serve it using your normal authorization, cache, and content-type rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For website screenshots rather than generated artwork, ScreenshotNeo is a website screenshot API and MCP server for developers. Its single GET request returns a screenshot as PNG, JPEG, or WebP, or a PDF. One cURL example:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Cookie banners are accepted or removed before capture, along with supported newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. An MCP server exposes screenshot and page-information tools to AI agents. The Free plan includes 1,000 shots per month without a card; paid plans begin at $5 for 3,000 shots.

Sign up for 1,000 free screenshots a month with no card.

Frequently Asked Questions

Can I use any PHP image-generation SDK with OpenAI?

No. A PHP SDK must support the provider’s API and the workflow you choose; check the client package documentation and compatibility before integrating it.

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

Does this PHP example generate a screenshot?

No. OpenAI image generation creates artwork from prompts or edits. Website screenshots capture rendered web pages; ScreenshotNeo is a separate API for that task.

Should I use the Image API or Responses API for image generation?

Use the Image API for a direct generation or edit request, and consider Responses API when image work is part of a conversation or multi-turn editing flow.

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.