ChatGPT API integration showcased in PHP. User input triggers AJAX call to PHP, generating ChatGPT responses, enhancing interaction.

In today’s digital era, chatbots have become an essential tool for businesses to enhance customer engagement and streamline communication. OpenAI’s ChatGPT API provides developers with a powerful and versatile platform to build intelligent chatbots.

In this article, we will walk you through the process of integrating the ChatGPT API in PHP with the help of a practical example. Here, we will take the query as user input and get a ChatGPT response using API and display it to the user using an AJAX call.

Obtain an API Key

Before we begin, you need to sign up for the OpenAI API and obtain an API key. Visit the OpenAI website and follow the instructions to get your API key. Once you have your API key, we can move on to the next step.

Creating HTML Form

To integrate the ChatGPT API into your PHP application, ensure that you have a PHP environment set up on your server or local machine. Make sure you have PHP installed and running.

Now, let’s create a simple HTML form that allows users to input their query or message. Open the text editor and create a new PHP file by index.php. However, you can use any existing page if you are implementing it into a live project. Just take a portion of the code from the following code as per your requirement:

<!DOCTYPE html>
<html>
<head>
    <title>ChatGPT Integration</title>
</head>
<body>
    <h1>ChatGPT Integration In PHP with Example </h1>
    <div id="chatbox"></div>
    <form id="chatForm" method="post">
        <input type="text" id="userMessage" placeholder="Enter your query..." required>
        <button type="submit">Send</button>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#chatForm").submit(function(e){
                e.preventDefault();
                var userMessage = $("#userMessage").val();
                $.ajax({
                    url: "chat.php",
                    method: "POST",
                    data: {message: userMessage},
                    success: function(response){
                        $("#chatbox").append("<p><strong>You:</strong> " + userMessage + "</p>");
                        $("#chatbox").append("<p><strong>ChatGPT:</strong> " + response + "</p>");
                        $("#userMessage").val("");
                    }
                });
            });
        });
    </script>
</body>
</html>

In the above example, we have created a simple form with one input and submit button. We have also used jQuery. Once a user clicks on submit button it will send a request to our PHP API and display a response back to the user. Here, we have also cleared user query input.

Create the PHP Chat Endpoint

In the same directory as your index.php file, create a new PHP file called chat.php. This file will handle the AJAX request and interact with the ChatGPT API and return the ChatGPT response to the AJAX call. Add the following code to the chat.php file:

<?php
$apiKey = "YOUR_API_KEY_HERE";
$userMessage = $_POST['message'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.openai.com/v1/chat/completions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "model=davinci-codex&messages=[{\"role\":\"system\",\"content\":\"You are a helpful assistant.\"},{\"role\":\"user\",\"content\":\"" . $userMessage . "\"}]");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer " . $apiKey;
curl_setopt($ch

, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

$response = json_decode($result);
echo $response->choices[0]->message->content;
?>

Make sure to replace YOUR_API_KEY_HERE with your actual API key obtained from OpenAI. Here, it will send an API request to OpenAI for ChatGPT and pass user input as a parameter. If it gets success response then it will print the response’s content otherwise show an error to the user.

Testing the application

Now, open your web browser and navigate to the index.php file of your project. You will see a form with an input field. Enter your message and click the “Send” button. ChatGPT’s response will be displayed below the input field. The conversation history will also be visible as you continue interacting with the chatbot.

Conclusion

In this example, we have successfully integrated the ChatGPT API into your PHP application. You can now create interactive chatbots that provide meaningful responses to user input. You can customize this functionality further. Please refer to the OpenAI documentation for more details on the ChatGPT API and explore the available customization options.