How can I connect my website chatbot to the OpenAI API using PHP?
Asked on Sep 02, 2025
Answer
To connect your website chatbot to the OpenAI API using PHP, you'll need to make HTTP requests to the API endpoint with the appropriate headers and payload. This involves using PHP's cURL functions to send a POST request to OpenAI's API with your API key and the desired prompt.
<!-- BEGIN COPY / PASTE -->
$apiKey = 'your-openai-api-key';
$url = 'https://api.openai.com/v1/engines/davinci-codex/completions';
$data = [
'prompt' => 'Hello, how can I assist you today?',
'max_tokens' => 150
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
<!-- END COPY / PASTE -->Additional Comment:
- Ensure you replace 'your-openai-api-key' with your actual OpenAI API key.
- Modify the 'prompt' and 'max_tokens' parameters according to your chatbot's requirements.
- Handle the API response appropriately to display the chatbot's response on your website.
- Consider implementing error handling for the cURL request to manage potential API errors.
Recommended Links: