How quickly get started with Open-AI DALL-E using PHP

Official documentation of Open AI gives 3 type of examples – NodeJS SDK, Python SDK and raw CURL.

I know there are several 3rd party PHP SDK-s in Github. But i also know most of excited testers would like to get started directly, without installing SDK and reading docs.

So, let’s implement raw CURL directly into PHP code and make DALL-E working in 1 minute.

You must get your API token here: https://beta.openai.com/account/api-keys

Once you have a key, just use this PHP snippet for DALL-E image generation:

<?php
$number=1; //change it then
$resolution='512x512';
$apikey=YOUR_KEY_HERE;
$yourinput='Imagine Nigara waterwall on Mars';
exec('
curl https://api.openai.com/v1/images/generations \
  -H \'Content-Type: application/json\' \
  -H "Authorization: Bearer '.$apikey.'" \
  -d \'{
    "prompt": "'.$yourinput.'",
    "n": 1,
    "size": "'.$resolution.'"
  }\'
 ',$output, $return_var);


file_put_contents("image".$number.".data",$output);
$foutput=file_get_contents("image".$number.".data");
$joutput=json_decode($foutput,true);
if(isset($joutput["data"][0]["url"])){
  file_put_contents("image".$number.".png",file_get_contents($joutput["data"][0]["url"]));
  echo '<a href="'.$joutput["data"][0]["url"].'">DOWNLOAD</a><br>';
}
else {
    print_r($output); //something went wrong
}

echo 'done'

That’s all. This piece of code will give you a saved PNG image without needing installing SDK or other libraries.

And here are some sample generated images with this code


Discover more from WP DEV - Elvin Haci

Subscribe to get the latest posts sent to your email.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from WP DEV - Elvin Haci

Subscribe now to keep reading and get access to the full archive.

Continue reading