Artificial Intelligence 5 min read

How to Build an Intelligent Chat Application with ChatGPT using PHP

This tutorial guides readers through building an AI‑powered chat application using PHP and the OpenAI ChatGPT API, covering environment setup, Composer dependency installation, backend PHP integration, a simple HTML/JavaScript front‑end, and how to run the app locally for interactive conversational experiences.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Build an Intelligent Chat Application with ChatGPT using PHP

With the rise of artificial intelligence, chatbots play a crucial role in social entertainment, and ChatGPT by OpenAI provides a powerful conversational model. This article explains how to create an intelligent chat application using PHP, covering the required environment, dependency installation, backend PHP code that calls the ChatGPT API, a simple HTML/JavaScript front‑end, and how to run the application locally.

Preparation : Install PHP ≥ 7.2, obtain an OpenAI API key, ensure Composer is installed, and set up a project directory.

Install the OpenAI PHP client with:

composer require openai/openai-api

Backend code : Create index.php and add the following PHP script, which loads the Composer autoloader, creates an OpenAI client, receives POSTed user messages and chat history, calls the gpt-3.5-turbo model, and echoes the response.

<?php
require 'vendor/autoload.php'; // import dependencies

use OpenAI\OpenAI;

$openai = new OpenAI([
    'apiKey' => 'your-api-key' // replace with your API key
]);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $message = $_POST['message'];      // user input
    $chat_log = $_POST['chat_log'];   // chat history

    // Call ChatGPT API
    $response = $openai->chat([
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'system', 'content' => 'You are a helpful assistant.'],
            ['role' => 'user', 'content' => $message]
        ],
        'chatLog' => $chat_log,
    ]);

    $result = $response['choices'][0]['message']['content'];
    echo $result;
}
?>

Front‑end interface : Add a minimal HTML form and JavaScript that displays the conversation, sends the user message and chat log to index.php via AJAX, and appends the ChatGPT reply.

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Chat Application&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Chat Application&lt;/h1&gt;
  &lt;div id="chatbox"&gt;
    &lt;div id="chatlog"&gt;&lt;/div&gt;
    &lt;input type="text" id="message" placeholder="Type your message here"&gt;
    &lt;button onclick="sendMessage()"&gt;Send&lt;/button&gt;
  &lt;/div&gt;

  &lt;script&gt;
    var chatLog = [];

    function sendMessage() {
      var message = document.getElementById('message').value;
      var chatLogElement = document.getElementById('chatlog');

      chatLogElement.innerHTML += '&lt;p&gt;User: ' + message + '&lt;/p&gt;';

      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'index.php', true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.onload = function () {
        if (xhr.status === 200) {
          chatLogElement.innerHTML += '&lt;p&gt;ChatGPT: ' + xhr.responseText + '&lt;/p&gt;';
          chatLog.push(message);
          chatLog.push(xhr.responseText);
        }
      };
      xhr.send('message=' + encodeURIComponent(message) + '&amp;chat_log=' + encodeURIComponent(JSON.stringify(chatLog)));
    }
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

Running the app : Start PHP’s built‑in server with php -S localhost:8000 and open http://localhost:8000 in a browser.

Conclusion : By following these steps you can quickly build a ChatGPT‑powered chat service that delivers natural, personalized conversations, and you can further customize the code and UI to suit your specific scenario.

AIChatGPTWeb DevelopmentphpAPIchatbot
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.