Skip to content

Instantly share code, notes, and snippets.

@mahadirz
Created March 17, 2023 11:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahadirz/dfb75777acad45c254e204c96a609e3a to your computer and use it in GitHub Desktop.
Save mahadirz/dfb75777acad45c254e204c96a609e3a to your computer and use it in GitHub Desktop.
simple chatgpt prompt using php
<?php
$completion = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Your OpenAI API key
$apiKey = '';
// The message you want to send to OpenAI
$message = $_POST['message'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "'.$message.'"
}
]
}',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
curl_close($curl);
// Process the response from the OpenAI API
$json = json_decode($response);
$completion = $json->choices[0]->message->content;
// echo $response;
// echo $completion;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT OpenAI API Example</title>
</head>
<body>
<h1>ChatGPT OpenAI API Example</h1>
<form method="post" action="process_input.php">
<label for="message">Message:</label>
<input type="text" id="message" name="message"><br><br>
<input type="submit" value="Submit">
</form>
<p>
<?php
if($completion){
echo $completion;
}
?>
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment