ChatGPT API Integration in PHP

The ChatGPT API, provided by OpenAI, enables developers to access the powerful language model capabilities of ChatGPT. By integrating this API into your PHP applications, you can create interactive and intelligent conversational agents that can understand and respond to user inputs in a human-like manner.

Integrating the ChatGPT API into a PHP application allows you to build AI-powered features such as chatbots, virtual assistants, content generators, and customer support tools. In this tutorial, we will learn how to integrate the ChatGPT API in PHP using OpenAI’s Chat API to build AI-powered applications.

πŸ”₯ What You Will Learn

  • How the ChatGPT API works
  • How to set up a PHP environment for API integration
  • How to obtain and configure the OpenAI API key
  • How to configure OpenAI API in PHP
  • Building a ChatGPT client in PHP
  • How to send requests and handle responses from the ChatGPT API
  • Handling conversations and system prompts
  • Creating an AJAX-powered chat interface for user interaction
  • Error handling and best practices

πŸ“‹ Prerequisites

Before you begin, ensure you have the following:

  • PHP 7.4 or later
  • PHP cURL extension enabled
  • An OpenAI API Key
  • A local or live web server (XAMPP, WAMP, LAMP, etc.)

πŸ”‘ Get Your OpenAI API Key

To interact with the ChatGPT API, you need an API key from OpenAI. Follow these steps to obtain your API key:

  1. Sign up or log in to your OpenAI account at OpenAI Platform.
  2. Navigate to the API Keys section.
  3. Create a new API key and copy it.

πŸ“ Project Structure Overview

Before diving into the code, let’s take a look at the project structure:

chatgpt_api_integration_in_php/
β”œβ”€β”€ config.php
β”œβ”€β”€ ChatGPTClient.php
β”œβ”€β”€ api.php
└── index.html

Each file has a specific responsibility, making the integration easy to maintain and extend.

  • config.php: Contains configuration settings, including the OpenAI API key and model selection.
  • ChatGPTClient.php: A PHP class that handles communication with the ChatGPT API.
  • api.php: The backend script that processes AJAX requests from the frontend and interacts with the ChatGPTClient.
  • index.html: The frontend interface (chat UI) where users can interact with the ChatGPT-powered chatbot.

πŸš€ Let’s get started with ChatGPT API Integration in PHP step by step, using a ready-made and production-ready script.

API Configuration (config.php)

The config.php file contains essential configuration settings for the ChatGPT API integration. Here, you will define your OpenAI API key, select the model to use, and set other parameters like temperature and maximum tokens.

<?php 
// Your OpenAI API Key (get it from https://platform.openai.com/api-keys)
define('OPENAI_API_KEY''your-api-key-here');

// API Endpoint
define('OPENAI_API_ENDPOINT''https://api.openai.com/v1/chat/completions');

// Model to use
define('OPENAI_MODEL''gpt-3.5-turbo'); //gpt-5.2, gpt-5-nano

// Request timeout (in seconds)
define('REQUEST_TIMEOUT'30);

// Temperature (controls randomness: 0 = deterministic, 1 = random)
define('TEMPERATURE'0.7);

// Maximum tokens in response
define('MAX_TOKENS'2000);
?>

Make sure to replace 'your-api-key-here' with your actual OpenAI API key obtained from the OpenAI platform.

ChatGPT Client Class (ChatGPTClient.php)

The ChatGPTClient.php file contains a PHP class that encapsulates the logic for communicating with the ChatGPT API. This class handles sending requests and processing responses.

Some of the key features of this class include:

  • Initialization with API key, model, timeout, temperature, and max tokens.
  • Building request payloads for the ChatGPT API.
  • Sending HTTP requests to the ChatGPT API via cURL.
  • Error handling and response processing.
  • Support for conversation history and system roles.

Core Method: sendMessage()
This method sends a user prompt along with optional conversation history and returns the AI response.
It automatically:

  • Prepends system prompts
  • Appends user messages
  • Parses the API response
<?php 
class ChatGPTClient
{
    private 
$apiKey;
    private 
$endpoint;
    private 
$model;
    private 
$timeout;
    private 
$temperature;
    private 
$maxTokens;
    private 
$lastError;

    
/**
     * Constructor
     * 
     * @param string $apiKey OpenAI API Key
     * @param string $model Model to use (default: gpt-3.5-turbo)
     * @param int $timeout Request timeout in seconds
     * @param float $temperature Temperature for response (0-2)
     * @param int $maxTokens Maximum tokens in response
     */
    
public function __construct(
        
$apiKey,
        
$model 'gpt-3.5-turbo',
        
$timeout 30,
        
$temperature 0.7,
        
$maxTokens 2000
    
) {
        
$this->apiKey $apiKey;
        
$this->model $model;
        
$this->endpoint 'https://api.openai.com/v1/chat/completions';
        
$this->timeout $timeout;
        
$this->temperature $temperature;
        
$this->maxTokens $maxTokens;
        
$this->lastError null;
    }

    
/**
     * Send a message to ChatGPT and get a response
     * 
     * @param string $message User message
     * @param array $conversationHistory Previous messages for context (optional)
     * @return string|false Response from ChatGPT or false on failure
     */
    
public function sendMessage($message$conversationHistory = [])
    {
        try {
            
// Prepare messages array
            
$messages $conversationHistory;
            
$messages[] = [
                
'role' => 'user',
                
'content' => $message
            
];

            
// Prepare request payload
            
$payload = [
                
'model' => $this->model,
                
'messages' => $messages,
                
'temperature' => $this->temperature,
                
'max_tokens' => $this->maxTokens
            
];

            
// Send request
            
$response $this->makeRequest($payload);

            if (
$response === false) {
                return 
false;
            }

            
// Extract response content
            
if (isset($response['choices'][0]['message']['content'])) {
                return 
trim($response['choices'][0]['message']['content']);
            }

            
$this->lastError 'Invalid response format from API';
            return 
false;

        } catch (
Exception $e) {
            
$this->lastError 'Exception: ' $e->getMessage();
            return 
false;
        }
    }

    
/**
     * Make HTTP request to OpenAI API
     * 
     * @param array $payload Request payload
     * @return array|false Response data or false on failure
     */
    
private function makeRequest($payload)
    {
        
$ch curl_init();

        
$options = [
            
CURLOPT_URL => $this->endpoint,
            
CURLOPT_RETURNTRANSFER => true,
            
CURLOPT_TIMEOUT => $this->timeout,
            
CURLOPT_HTTPHEADER => [
                
'Content-Type: application/json',
                
'Authorization: Bearer ' $this->apiKey
            
],
            
CURLOPT_POST => true,
            
CURLOPT_POSTFIELDS => json_encode($payload)
        ];

        
curl_setopt_array($ch$options);

        
$response curl_exec($ch);
        
$httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
        
$curlError curl_error($ch);

        
curl_close($ch);

        
// Check for cURL errors
        
if ($curlError) {
            
$this->lastError 'cURL error: ' $curlError;
            return 
false;
        }

        
// Check HTTP status code
        
if ($httpCode !== 200) {
            
$this->handleHttpError($httpCode$response);
            return 
false;
        }

        
// Decode response
        
$decodedResponse json_decode($responsetrue);

        if (
json_last_error() !== JSON_ERROR_NONE) {
            
$this->lastError 'JSON decode error: ' json_last_error_msg();
            return 
false;
        }

        
// Check for API errors
        
if (isset($decodedResponse['error'])) {
            
$this->lastError 'API Error: ' $decodedResponse['error']['message'];
            return 
false;
        }

        return 
$decodedResponse;
    }

    
/**
     * Handle HTTP errors from API
     * 
     * @param int $httpCode HTTP status code
     * @param string $response Response body
     */
    
private function handleHttpError($httpCode$response)
    {
        
$errorMessages = [
            
400 => 'Bad Request - Invalid parameters',
            
401 => 'Unauthorized - Invalid API key',
            
403 => 'Forbidden - Access denied',
            
429 => 'Too Many Requests - Rate limit exceeded',
            
500 => 'Internal Server Error',
            
503 => 'Service Unavailable'
        
];

        
$message $errorMessages[$httpCode] ?? "HTTP Error $httpCode";

        
// Try to get more details from response
        
$decoded json_decode($responsetrue);
        if (isset(
$decoded['error']['message'])) {
            
$message .= ': ' $decoded['error']['message'];
        }

        
$this->lastError $message;
    }

    
/**
     * Get the last error
     * 
     * @return string|null Last error message or null if no error
     */
    
public function getLastError()
    {
        return 
$this->lastError;
    }

    
/**
     * Test the API connection
     * 
     * @return bool True if connection successful, false otherwise
     */
    
public function testConnection()
    {
        
$response $this->sendMessage('Hello');
        return 
$response !== false;
    }

    
/**
     * Clear conversation history
     * 
     * @return void
     */
    
public function clearHistory()
    {
        
// This is handled in the application logic
        // This method is here for API completeness
    
}
}
?>

ChatGPTClient Class Usage Examples

The following examples demonstrate how to use the ChatGPTClient class to interact with the OpenAI ChatGPT API. Each example includes code snippets and explanations to help you understand how to implement various functionalities.

First, ensure you include the necessary files and initialize the ChatGPTClient with your OpenAI API key:

// Include configuration and client class 
require_once 'config.php';
require_once 
'ChatGPTClient.php';

// Initialize the ChatGPT client
$client = new ChatGPTClient(
    
OPENAI_API_KEY,
    
OPENAI_MODEL,
    
REQUEST_TIMEOUT,
    
TEMPERATURE,
    
MAX_TOKENS
);

Example 1: Simple message

$response $client->sendMessage('What is the capital of France?'); 
if (
$response) {
    echo 
"Q: What is the capital of France?\n";
    echo 
"A: " $response "\n\n";
} else {
    echo 
"Error: " $client->getLastError() . "\n\n";
}

Example 2: Conversation with history

$conversationHistory = []; 

// First message
$userMessage1 "Tell me about machine learning";
$response1 $client->sendMessage($userMessage1$conversationHistory);
if (
$response1) {
    echo 
"You: " $userMessage1 "\n";
    echo 
"Bot: " $response1 "\n\n";
    
    
// Add to history
    
$conversationHistory[] = ['role' => 'user''content' => $userMessage1];
    
$conversationHistory[] = ['role' => 'assistant''content' => $response1];
}

// Follow-up message
$userMessage2 "What are the main types?";
$response2 $client->sendMessage($userMessage2$conversationHistory);
if (
$response2) {
    echo 
"You: " $userMessage2 "\n";
    echo 
"Bot: " $response2 "\n\n";
    
    
// Add to history
    
$conversationHistory[] = ['role' => 'user''content' => $userMessage2];
    
$conversationHistory[] = ['role' => 'assistant''content' => $response2];
}

Example 3: With system prompt for role-playing

$systemPromptHistory = [ 
    [
'role' => 'system''content' => 'You are a helpful Python programming expert.']
];

$response3 $client->sendMessage('How do I read a file in Python?'$systemPromptHistory);
if (
$response3) {
    echo 
"You: How do I read a file in Python?\n";
    echo 
"Bot: " $response3 "\n\n";
} else {
    echo 
"Error: " $client->getLastError() . "\n\n";
}

Example 4: Test connection

if ($client->testConnection()) { 
    echo 
"Connection to OpenAI API: SUCCESS\n";
} else {
    echo 
"Connection to OpenAI API: FAILED\n";
    echo 
"Error: " $client->getLastError() . "\n";
}

🧩 Now, let’s look at how the api.php file utilizes the ChatGPTClient class to handle AJAX requests from the frontend chat interface.

Backend API Handler (api.php)

The api.php file serves as the backend endpoint that processes AJAX requests from the frontend chat interface. It performs the following tasks:

  • Includes necessary files and initializes the ChatGPTClient.
  • Validates incoming requests and user prompts.
  • Handles conversation history to maintain context.
  • Sends the user prompt to the ChatGPTClient and retrieves the response.
  • Returns the AI response as a JSON object to the frontend.
<?php 
header
('Content-Type: application/json');

require_once 
'config.php';
require_once 
'ChatGPTClient.php';

// Check if API key is configured
if (empty(OPENAI_API_KEY) || OPENAI_API_KEY === 'your-api-key-here') {
    echo 
json_encode([
        
'success' => false,
        
'error' => 'API key is not configured. Please set your OpenAI API key in config.php'
    
]);
    exit;
}

try {
    
$input json_decode(file_get_contents('php://input'), true);
    
    if (!isset(
$input['message'])) {
        echo 
json_encode([
            
'success' => false,
            
'error' => 'Message is required'
        
]);
        exit;
    }

    
$message trim($input['message']);
    if (empty(
$message)) {
        echo 
json_encode([
            
'success' => false,
            
'error' => 'Message cannot be empty'
        
]);
        exit;
    }

    
// Get conversation history if provided
    
$history = isset($input['history']) ? $input['history'] : [];

    
// Initialize client
    
$client = new ChatGPTClient(
        
OPENAI_API_KEY,
        
OPENAI_MODEL,
        
REQUEST_TIMEOUT,
        
TEMPERATURE,
        
MAX_TOKENS
    
);

    
// Send message
    
$response $client->sendMessage($message$history);

    if (
$response === false) {
        echo 
json_encode([
            
'success' => false,
            
'error' => $client->getLastError()
        ]);
        exit;
    }

    echo 
json_encode([
        
'success' => true,
        
'response' => $response,
        
'message' => $message
    
]);

} catch (
Exception $e) {
    echo 
json_encode([
        
'success' => false,
        
'error' => 'Exception: ' $e->getMessage()
    ]);
}
?>

Frontend Chat Interface (index.html)

The index.html file provides a simple and user-friendly chat interface where users can interact with the ChatGPT-powered chatbot. Key features include:

  • A chat window displaying conversation history.
  • An input field for users to type their messages.
  • A send button to submit messages.
  • AJAX functionality to send user messages to the backend without reloading the page.
  • Dynamic updating of the chat window with user and AI messages.

Chat Interface HTML:
Define the chat interface structure with a chat window, input field, and buttons.

<div class="input-section">
    <div class="input-wrapper">
        <input 
            type="text" 
            id="messageInput" 
            placeholder="Type your message here..."
            autocomplete="off"
        >
        <button id="sendBtn" onclick="sendMessage()">Send</button>
    </div>
    <button class="clear-btn" onclick="clearChat()">Clear</button>
</div>

AJAX Functionality (JavaScript):
Call the backend API (api.php) using AJAX to send user messages and receive AI responses.

<script>
    const chatMessages = document.getElementById('chatMessages');
    const messageInput = document.getElementById('messageInput');
    const sendBtn = document.getElementById('sendBtn');
    let conversationHistory = [];
    let isLoading = false;

    // Send message on Enter key
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !isLoading) {
            sendMessage();
        }
    });

    async function sendMessage() {
        const message = messageInput.value.trim();
        
        if (!message) return;
        if (isLoading) return;

        isLoading = true;
        sendBtn.disabled = true;
        messageInput.disabled = true;

        // Add user message to chat
        addMessage(message, 'user');
        messageInput.value = '';

        // Show loading indicator
        const loadingElement = showLoadingIndicator();

        try {
            const response = await fetch('api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    history: conversationHistory
                })
            });

            const data = await response.json();

            // Remove loading indicator
            loadingElement.remove();

            if (data.success) {
                // Add bot response to chat
                addMessage(data.response, 'assistant');

                // Update conversation history
                conversationHistory.push({
                    role: 'user',
                    content: message
                });
                conversationHistory.push({
                    role: 'assistant',
                    content: data.response
                });
            } else {
                addMessage('Error: ' + data.error, 'error');
            }
        } catch (error) {
            loadingElement.remove();
            addMessage('Network error: ' + error.message, 'error');
        } finally {
            isLoading = false;
            sendBtn.disabled = false;
            messageInput.disabled = false;
            messageInput.focus();
        }
    }

    function addMessage(text, role) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message ' + role;

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.innerHTML = escapeHtml(text) + 
            '<div class="timestamp">' + new Date().toLocaleTimeString() + '</div>';

        messageDiv.appendChild(contentDiv);
        chatMessages.appendChild(messageDiv);

        // Auto scroll to bottom
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function showLoadingIndicator() {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message assistant';

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.innerHTML = '<div class="loading"><span></span><span></span><span></span></div>';

        messageDiv.appendChild(contentDiv);
        chatMessages.appendChild(messageDiv);

        // Auto scroll to bottom
        chatMessages.scrollTop = chatMessages.scrollHeight;

        return messageDiv;
    }

    function clearChat() {
        if (confirm('Are you sure you want to clear the chat?')) {
            chatMessages.innerHTML = '<div class="message system"><div class="message-content">Chat cleared. Start a new conversation!</div></div>';
            conversationHistory = [];
            messageInput.focus();
        }
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Focus input on load
    messageInput.focus();
</script>

πŸ” Security & Best Practices

  • Store API keys securely
  • Use environment variables in production
  • Limit MAX_TOKENS to control costs
  • Cache responses where possible
  • Log errors for monitoring
  • Sanitize user input

🎯 Use Cases of ChatGPT API in PHP

This ChatGPT PHP integration can be utilized in various applications, including:

  • AI chatbots for websites
  • Customer support systems
  • Virtual assistants
  • Content generation tools
  • Educational platforms
  • SaaS AI features
  • Interactive storytelling applications

πŸš€ Conclusion

You have successfully learned how to integrate the ChatGPT API in PHP using a clean, scalable, and production-ready approach. This implementation is ideal for real-world applications and can be extended with authentication, database storage, or advanced prompt engineering. If you are building modern PHP applications, ChatGPT integration is a powerful way to enhance user experience and automation.

Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request

Leave a reply

construction Need this implemented in your project? Request Implementation Help β†’ keyboard_double_arrow_up