|
This is a barebones example using OpenAI’s DALL-E image URL generation with PHP from a user prompt on a web page.
Image generation is in beta as of this writing.
The picture of the cat wearing a space helmet with a illustrative AI model as star space in the background was generated using the code in this article.
I started with GPT-4 to assist in the code writing. It did a great job of hacking out the code and it worked. However because its knowledge cutoff date of September 2021 unnecessary code was included.
You do need an account and an API key from the OpenAI Platform. If you are using ChatGPT then you have an account.
The user interface style is bare but gets the job done for a learning example.
How you load the API key into your PHP code is up to you. Here is how I did it. A hidden file contains the API key on a single line. The file name I used is .open-php-curl-env
. You can use any file name. Here is my code for that.
// Load the OpenAI API key
// Create a text file (name optional) with your OpenAI API Key on the first line.
$api_key = file_get_contents('.openai-php-curl-env');
In addition to the API key you need credits with OpenAI. If you have a new account they you might have a free grant of credits.
PHP has to use the cURL library to communicate with OpenAI’s API. The communication endpoint is https://api.openai.com/v1/images/generations.
The endpoint request body has various options. I put them into an array for use in cURL.
$data = array(
"prompt" => $_POST['prompt'],
"size" => '512x512', //256x256, 512x512, or 1024x1024 pixels
"n" => 1, // Number of images
"response_format" => "url", //url | b64_json. URLs will expire after an hour.
);
The prompt is the user request text coming from the web page. There are four image sizes. Smaller has a faster response time and my guess is uses less credits.
You can get more than one image at a time. The example code only can handle one image in the response. As you will see the response has the image information in an array.
There are two response format values. The url
value returns a URL that expires after 1 hour. The b64_json
value returns image data. In either case you can copy or save the image from the web page. The b64_json
value cannot be used with this example. The code for returning a URL is slightly different and you can check that out at OpenAI DALL-E Image URL Generation with HTML, PHP, cURL, and Javascript AJAX.
The cURL code is boilerplate ready to plug in the values. Line 25 has the OpenAI API request endpoint. The request body data is inserted in JSON format on line 28. The api key is added on line 31.
The request is processed on line 33. If there is a cURL failure the error is dumped to the error log. The error log line is only necessary for testing and debugging.
// cURL processing
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/images/generations');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . $api_key;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response_raw = curl_exec($ch);
if (curl_errno($ch)) {
error_log('error: ' . curl_error($ch));
The next step is check if the OpenAI API succeeded and then extract the image’s URL. The response is in the JSON format. It is decoded on line 39. The lack of the error
key signifies success. We are doing nothing if there is an error. Line 37 can be uncommented if there are issues with the response value.
Line 42 shows were the image url is nested in the return data. The data key is an array. The request was limited to one image so the 0 index contains the url. If you requested more than one image on line 20, then you would have to modify this code along with the HTML and Javascript code appropriately.
}else{
//error_log('$response_raw: ' . print_r($response_raw,true));
// Decode the JSON response
$json_response = json_decode($response_raw, true);
if (!isset($jsonResponse['error'])) {
// The image URL in the response
$imageUrl = $json_response['data'][0]['url'];
$rtn_val['image-url'] = $imageUrl;
$rtn_val['success'] = true;
}
The $rtn_val
variable is my coding style for returning data to the front-end. The success
key is defaulted to false at the start of the file on line 4 and only set to true at this point. The image-url
key is also just a programmer’s choice on how to tag return data for the front end.
JSON format is used for AJAX, so the $rtn_val
is converted to JSON and sent on its way to the waiting front end.
//Respond with JSON content
header('Content-Type: application/json');
echo json_encode( $rtn_val );
How to handle AJAX request and response is a programmer’s choice. This is a basic learning example but some validation was added on lines 6 to 12.
The Javascript file AJAX is handled using jQuery is on lines 18 – 45. Line 37 tests for the success
key in the return data. If its true then on line 39 success user feedback along with the image URL is shown in the results
element for learning demonstration purposes. The image URL set to the img
element’s src
attribute on the next line. Negative user feedback is added on line 42 if the success
key is false.
function sendPromptAjax(){
//console.log('sendPromptAjax');
$('#results').html('...processing...');
let dataSend = {};
dataSend['prompt'] = $('#prompt').val();
//console.log("sendPromptAjax| dataSend", dataSend);
$.ajax(
{
type:"post",
url:"openai-image-01.php",
data:dataSend,
dataType:'json',
}
)
.done(
function(data, status){
//console.log("sendPromptAjax | done");
//console.log("sendPromptAjax | data", data);
//console.log("sendPromptAjax | status", status);
if (data.success){
console.log("sendPromptAjax | Success true");
$('#results').html('Success: ' + data['image-url']);
$("#open-ai-image").attr("src", data['image-url']);
}else{
$('#results').html('Request failed.');
}
}
)
The key HTML elements are on lines 23-26 of the HTML file.
<div><p class="text-align-left"><input id="prompt" type="text" placeholder="Enter a prompt" ><br>Ex: A white siamese cat.<br>A beautiful sunset over the mountains</p></div>
<div><p><button id="send">Send</button></p></div>
<div><image id="open-ai-image"/></div>
<div><p id="results"></p></div>
There are 5 files in total.
.openai-php-curl-env
openai-image-01.html
openai-image-01.css
openai-image-01.js
openai-image-01.php