Building a Chatbot with ChatGPT API and PHP

This article guides you through building a chatbot using the official ChatGPT API and native PHP cURL functions. You'll learn how to obtain an API key, configure your PHP environment, and write the code to send and receive messages from the ChatGPT endpoint. The tutorial uses only official documentation from OpenAI and PHP.net, ensuring compatibility and reliability. By following these steps, you’ll have a fully functional chatbot and understand best practices for SEO and maintainability.
Prerequisites
-
PHP 7.4 or later installed with cURL extension enabled on your system (verify via
phpinfo()
). (php.net) -
An OpenAI account with a valid API key. (platform.openai.com)
-
Basic knowledge of PHP and HTTP requests.
Step 1: Obtain Your OpenAI API Key
-
Log in to your OpenAI account at the OpenAI Platform and navigate to the API Keys section. (platform.openai.com)
-
Generate a new secret key and store it securely (e.g., in an environment variable).
export OPENAI_API_KEY="your_api_key_here"
Step 2: Setup Your PHP Environment
-
Ensure the cURL extension is enabled in your
php.ini
. Look forextension=curl
and uncomment if necessary, then restart your web server. (serpapi.com) -
Create a new PHP project folder and initialize it if using Composer (optional for autoloading). PHP’s native cURL functions remove the need for extra libraries. (php.net)
Step 3: Write the Chatbot Code
Create a file named chatbot.php
in your project directory:
<?php
// chatbot.php
// Load API key from environment
$apiKey = getenv('OPENAI_API_KEY');
// Prepare cURL session
$ch = curl_init('https://api.openai.com/v1/chat/completions');
// Define the request payload
$payload = json_encode([
'model' => 'gpt-4',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Hello, world!'],
],
]);
// Set cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute and handle response
$response = curl_exec($ch);
if ($error = curl_error($ch)) {
die('cURL Error: ' . $error);
}
curl_close($ch);
// Decode and display
$data = json_decode($response, true);
echo $data['choices'][0]['message']['content'];
-
We initialize a cURL session targeting the chat completions endpoint. (platform.openai.com)
-
The JSON payload follows the official Chat API schema with
model
andmessages
. (platform.openai.com) -
We set headers and options to POST JSON and return the response string. (php.net)
Step 4: Run and Test Your Chatbot
Execute the script from the command line or through your web server:
php chatbot.php
You should see ChatGPT’s response printed, e.g., “Hello! How can I assist you today?”
Conclusion
By following official documentation from OpenAI and PHP.net, you’ve created a simple yet powerful chatbot in PHP. This approach ensures you rely only on supported, maintained methods without external dependencies. Use this foundation to expand your chatbot with dynamic inputs, advanced context handling, or integration with web interfaces.