Software Development

How to Build a Chatbot with the OpenAI API and PHP

By vidu • • 16 min read • 64 views
How to Build a Chatbot with the OpenAI API and PHP

Chatbots can make websites more useful by answering questions, guiding visitors, summarizing information, and automating routine support tasks. With PHP and the OpenAI API, you can build a chatbot without creating and maintaining a language model yourself.

This guide explains how to build a simple web-based chatbot using PHP. You will learn how to send user messages to the OpenAI API, display the assistant’s response, preserve conversation context, protect your API key, and prepare the application for production use.

The example uses PHP with cURL and a small HTML interface. The same backend concepts can be applied to a PHP framework such as Laravel or Symfony.

What You Will Build

By the end of this tutorial, you will have a basic chatbot with:

  • A browser-based chat form
  • A PHP endpoint that communicates with OpenAI
  • Conversation history stored in the PHP session
  • Basic input validation and error handling
  • A protected API key that is never sent to the browser

The chatbot will be intentionally simple. A production application may also need user authentication, database storage, rate limiting, logging, content filtering, a streaming interface, and a knowledge base connected to your own documents.

How the Architecture Works

A chatbot built with PHP usually has three parts:

  1. Frontend: A web page where the user enters a message and reads the response.
  2. PHP application: Receives the message, adds conversation context, and sends a request to the OpenAI API.
  3. OpenAI API: Generates a response based on the instructions and messages provided by your application.

The browser should communicate with your PHP server, not directly with OpenAI. This protects your secret API key and gives you a central place to validate input, apply business rules, record usage, and limit requests.

Never place an OpenAI API key in JavaScript, HTML, a mobile app, or any code that is delivered directly to users. Treat the key like a database password.

Prerequisites

Before starting, make sure you have:

  • PHP 8.0 or later installed on a local server or hosting environment
  • The PHP cURL extension enabled
  • An OpenAI API account with API access configured
  • A valid API key stored securely on the server
  • Basic knowledge of PHP, HTML, and HTTP requests

You can use PHP’s built-in development server for local testing. In a project directory, a command such as php -S localhost:8000 can serve the application, provided PHP is installed correctly.

Step 1: Configure the API Key

For local development, set the API key as an environment variable rather than writing it directly into a PHP file. The exact way to define environment variables depends on your operating system and hosting provider.

For example, on a Unix-like system, you might define a variable in the shell before starting PHP:

export OPENAI_API_KEY="your-api-key-here"

On a production server, configure the variable through your hosting control panel, container configuration, process manager, or server environment. Do not commit the key to Git, upload it in a publicly accessible directory, or include it in an error message.

In PHP, retrieve the value with getenv():

$apiKey = getenv('OPENAI_API_KEY');

if (!$apiKey) {
    throw new RuntimeException('The OpenAI API key is not configured.');
}

If you use a local .env file, make sure that file is excluded from version control and blocked from public web access. Many PHP projects use an environment-variable library to load local configuration, but the security principle remains the same: secrets belong outside source code.

Step 2: Create the PHP API Client

The following function sends a request to the OpenAI Responses API using PHP cURL. The model name is configurable. Use a model that is available to your account and appropriate for your application’s cost, speed, and quality requirements.

<?php

function requestOpenAI(array $input, string $apiKey): array
{
    $payload = [
        'model' => 'gpt-4.1-mini',
        'instructions' => 'You are a helpful website support assistant. Answer clearly and honestly. If you do not know something, say so instead of inventing an answer.',
        'input' => $input,
        'store' => false
    ];

    $ch = curl_init('https://api.openai.com/v1/responses');

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        ],
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
        CURLOPT_TIMEOUT => 60
    ]);

    $responseBody = curl_exec($ch);
    $curlError = curl_error($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($responseBody === false) {
        throw new RuntimeException('The request could not be sent: ' . $curlError);
    }

    $response = json_decode($responseBody, true);

    if ($statusCode < 200 || $statusCode >= 300) {
        $message = $response['error']['message'] ?? 'The OpenAI API returned an error.';
        throw new RuntimeException($message);
    }

    if (!is_array($response)) {
        throw new RuntimeException('The API returned an invalid response.');
    }

    return $response;
}

This function performs several important tasks:

  • Builds a JSON request body
  • Sets the authorization header
  • Uses HTTPS to communicate with the API
  • Applies a timeout so a request cannot hang indefinitely
  • Checks the HTTP status code
  • Converts the JSON response into a PHP array

The instructions field defines the assistant’s general behavior. You can adapt it to your use case, such as a product support agent, booking assistant, internal knowledge assistant, or educational tutor. Keep instructions specific and avoid promising capabilities your application does not actually provide.

Step 3: Extract the Assistant’s Text

The Responses API returns a structured response. For a simple chatbot, your application needs the generated text. A small helper can inspect the output items and collect text segments.

function extractOutputText(array $response): string
{
    $parts = [];

    foreach ($response['output'] ?? [] as $item) {
        if (($item['type'] ?? null) !== 'message') {
            continue;
        }

        foreach ($item['content'] ?? [] as $content) {
            if (($content['type'] ?? null) === 'output_text') {
                $parts[] = $content['text'] ?? '';
            }
        }
    }

    $text = trim(implode('', $parts));

    if ($text === '') {
        throw new RuntimeException('The assistant returned no text.');
    }

    return $text;
}

Keeping response parsing in a separate function makes the application easier to test and update. API response formats can evolve, so isolating this logic prevents response-specific code from spreading throughout your project.

Step 4: Maintain Conversation History

A chatbot needs context. If the user says, “What are your opening hours?” and then asks, “What about on Sunday?”, the second question depends on the first answer. Your PHP application can send earlier messages along with the new message.

For a small demonstration, PHP sessions are convenient. Start a session and store an array of messages:

session_start();

if (!isset($_SESSION['chat_history'])) {
    $_SESSION['chat_history'] = [];
}

Each message should identify its role and contain its text. A simple history might look like this:

[
    [
        'role' => 'user',
        'content' => 'What are your opening hours?'
    ],
    [
        'role' => 'assistant',
        'content' => 'We are open from 9:00 AM to 5:00 PM on weekdays.'
    ]
]

When a new request arrives, append the user’s message, send the history to OpenAI, and append the assistant’s response after it succeeds.

$userMessage = trim($_POST['message'] ?? '');

if ($userMessage === '') {
    throw new InvalidArgumentException('Please enter a message.');
}

if (mb_strlen($userMessage) > 2000) {
    throw new InvalidArgumentException('Your message is too long.');
}

$_SESSION['chat_history'][] = [
    'role' => 'user',
    'content' => $userMessage
];

$response = requestOpenAI($_SESSION['chat_history'], $apiKey);
$assistantMessage = extractOutputText($response);

$_SESSION['chat_history'][] = [
    'role' => 'assistant',
    'content' => $assistantMessage
];

For long conversations, sending the entire history on every request can increase token usage and eventually exceed the model’s context limit. A practical solution is to retain only the most recent messages and periodically summarize older parts of the conversation.

Step 5: Create the Chat Endpoint

Now combine the pieces into an endpoint, such as chat.php. This endpoint accepts a POST request and returns JSON that the frontend can display.

<?php

session_start();
header('Content-Type: application/json; charset=utf-8');

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        throw new RuntimeException('Only POST requests are allowed.');
    }

    $apiKey = getenv('OPENAI_API_KEY');

    if (!$apiKey) {
        throw new RuntimeException('The server is not configured for chat requests.');
    }

    if (!isset($_SESSION['chat_history'])) {
        $_SESSION['chat_history'] = [];
    }

    $message = trim($_POST['message'] ?? '');

    if ($message === '') {
        throw new InvalidArgumentException('Please enter a message.');
    }

    if (mb_strlen($message) > 2000) {
        throw new InvalidArgumentException('Please keep messages under 2,000 characters.');
    }

    $_SESSION['chat_history'][] = [
        'role' => 'user',
        'content' => $message
    ];

    $response = requestOpenAI($_SESSION['chat_history'], $apiKey);
    $reply = extractOutputText($response);

    $_SESSION['chat_history'][] = [
        'role' => 'assistant',
        'content' => $reply
    ];

    echo json_encode([
        'success' => true,
        'reply' => $reply
    ], JSON_THROW_ON_ERROR);
} catch (Throwable $exception) {
    http_response_code(400);

    echo json_encode([
        'success' => false,
        'error' => $exception->getMessage()
    ]);
}

In a production system, do not expose detailed internal errors to visitors. Log technical details on the server and return a general message to the user. You should also distinguish validation errors from provider errors so the frontend can respond appropriately.

Step 6: Build a Simple Chat Interface

Create an HTML page with a message area and a form. The browser can submit the form using the Fetch API, while the API key remains safely on the PHP server.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PHP Chatbot</title>
</head>
<body>
    <main>
        <h1>Ask our assistant</h1>
        <div id="chat" aria-live="polite"></div>

        <form id="chat-form">
            <label for="message">Message</label>
            <input id="message" name="message" required maxlength="2000">
            <button type="submit">Send</button>
        </form>
    </main>

    <script>
        const form = document.querySelector('#chat-form');
        const input = document.querySelector('#message');
        const chat = document.querySelector('#chat');

        function addMessage(label, text) {
            const paragraph = document.createElement('p');
            paragraph.textContent = `${label}: ${text}`;
            chat.appendChild(paragraph);
        }

        form.addEventListener('submit', async (event) => {
            event.preventDefault();

            const message = input.value.trim();
            if (!message) return;

            addMessage('You', message);
            input.value = '';

            const body = new URLSearchParams({ message });

            try {
                const response = await fetch('chat.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body
                });

                const data = await response.json();

                if (!data.success) {
                    throw new Error(data.error || 'The request failed.');
                }

                addMessage('Assistant', data.reply);
            } catch (error) {
                addMessage('Error', error.message);
            }
        });
    </script>
</body>
</html>

The example uses textContent rather than assigning user or model output to innerHTML. This is an important defensive measure because model responses and user messages should be treated as untrusted text. If you intentionally support formatted Markdown or HTML, sanitize the converted output with a well-maintained sanitizer before rendering it.

Improving Conversation Storage

PHP sessions are suitable for a prototype, but they are not always the best choice for a real application. Session data may be lost, difficult to inspect, or unsuitable for users who access the chatbot from multiple devices.

For a production chatbot, consider storing conversations in a database. A typical schema might include:

  • A conversations table containing the user, title, creation time, and last activity
  • A messages table containing the conversation ID, role, content, and timestamp
  • Optional usage fields for token counts, latency, model, and request status

When a user sends a message, load only the relevant conversation, apply a message limit, call the API, and save the assistant’s response. Use prepared statements through PDO to prevent SQL injection.

Another option is to use a conversation identifier managed by your own application and send selected history on each request. This gives you more control over retention, privacy, and context than keeping unlimited messages in a session.

Security Practices You Should Implement

Protect the API key

Store secrets in environment variables or a secure secrets manager. Restrict file permissions, prevent accidental logging, and rotate the key if you suspect it has been exposed.

Validate input on the server

Browser-side validation improves usability, but it is not a security boundary. Validate message length, request method, content type, and authenticated user permissions in PHP.

Add authentication and authorization

If the chatbot is private, require users to sign in. Confirm that an authenticated user is allowed to access the selected conversation before loading or changing it.

Use CSRF protection

For session-based applications, protect state-changing POST requests with a CSRF token. Same-origin requests and secure cookie settings are also important. Configure cookies with appropriate Secure, HttpOnly, and SameSite attributes.

Limit abuse

Every API call can consume paid resources. Add rate limits per user, session, IP address, or account. Enforce maximum message lengths and consider daily or monthly usage quotas.

Handle sensitive information carefully

Decide what information your application is allowed to send to an external AI provider. Avoid collecting unnecessary personal data. Define retention rules, protect logs, and make your privacy notice consistent with your actual data flows.

Controlling the Chatbot’s Behavior

The quality of a chatbot depends on more than the model. Clear application instructions and reliable business data are equally important.

A useful instruction might specify:

  • The assistant’s role and target audience
  • The tone and reading level to use
  • Which topics are within scope
  • What to do when information is missing
  • When to direct a user to a human representative
  • Formatting rules for answers

For example, a support chatbot should not invent product policies, delivery estimates, or account details. Tell it to rely only on information supplied by your application and to state when it cannot verify an answer.

Connecting the Chatbot to Your Own Data

A general-purpose model may not know your company’s current policies, inventory, documentation, or private records. To answer questions about your business, your PHP application must provide relevant information at request time.

For a small project, you can retrieve a short set of relevant records from your database and include them as context. For larger document collections, a retrieval-augmented generation workflow is more appropriate:

  1. Split documents into manageable sections.
  2. Create embeddings for those sections using an embedding model.
  3. Store the vectors in a suitable search system.
  4. Convert the user’s question into a search query or embedding.
  5. Retrieve the most relevant sections.
  6. Send those sections to the chatbot with clear instructions to use them as source context.

Retrieval does not guarantee a correct answer. You should still test relevance, handle outdated documents, limit the amount of context, and provide a way for users to contact a person when the answer is uncertain.

Managing Costs and Performance

Chatbot cost is influenced by the model, the amount of input and output text, and the number of requests. Sending a complete conversation history on every turn can become expensive and slow.

To improve efficiency:

  • Choose a model that matches the task instead of always using the most capable option.
  • Keep system instructions concise and specific.
  • Limit message length and maximum conversation history.
  • Summarize older messages when a conversation becomes long.
  • Cache stable answers where appropriate.
  • Use asynchronous processing for tasks that do not require an immediate reply.
  • Track request duration, failures, and usage information without storing unnecessary personal data.

Set reasonable cURL timeouts and display a helpful loading state in the interface. A chatbot that gives no feedback during a slow request feels broken even when the backend is working normally.

Streaming Responses

A standard request waits until the complete answer is ready. Streaming can display output progressively, which often makes the interface feel faster. Implementing streaming requires a different response-handling approach in PHP because the server must forward incremental events to the browser instead of returning one completed JSON object.

For a first version, regular responses are easier to implement and debug. Add streaming after you have reliable authentication, error handling, cancellation behavior, and frontend rendering. When streaming text, continue to treat all received content as untrusted output and avoid unsafe HTML insertion.

Testing Your PHP Chatbot

Test the application with more than a few successful questions. Useful test cases include:

  • An empty message
  • A message longer than the permitted limit
  • An invalid or missing API key
  • A network timeout
  • An API error or rate-limit response
  • A conversation with many turns
  • Unexpected characters and HTML-like input
  • Multiple users using separate sessions
  • Unauthenticated access to private conversations

Also test the assistant’s behavior. Ask questions outside its scope, provide ambiguous requests, and check whether it admits uncertainty instead of confidently creating facts. Save representative test cases so future prompt or model changes can be evaluated consistently.

Common Mistakes to Avoid

Calling OpenAI directly from the browser

This exposes your key and allows anyone to use your account through your frontend. Route requests through PHP.

Trusting model output as HTML

Model output is text, not trusted markup. Render it safely or sanitize it before allowing formatting.

Keeping unlimited history

Unlimited history increases latency, cost, and the chance of exceeding context limits. Apply a retention and summarization strategy.

Returning raw exceptions to users

Detailed exceptions can reveal implementation information. Log them securely and return a clear, limited user-facing message.

Assuming the chatbot is always correct

Language models can misunderstand questions or produce inaccurate answers. Use trusted application data, define escalation paths, and make important actions require confirmation.

From Prototype to Production

A basic PHP chatbot can be built in a short time, but production readiness requires careful engineering. Before launch, review the following checklist:

  • API keys are stored outside the codebase and are never sent to clients.
  • All requests use HTTPS.
  • Input validation, CSRF protection, and authentication are implemented where needed.
  • Rate limits and usage controls protect your budget.
  • Conversation data has clear retention and deletion rules.
  • Errors are logged securely without exposing sensitive content.
  • Responses are rendered safely in the browser.
  • The chatbot has clear scope and escalation instructions.
  • Timeouts, retries, and provider failures have been tested.
  • Model and API behavior are monitored after deployment.

Conclusion

Building a chatbot with the OpenAI API and PHP involves more than sending a question to an endpoint. A dependable implementation needs a secure server-side integration, controlled conversation history, safe rendering, validation, usage limits, and clear instructions for the assistant.

PHP’s cURL extension is enough to create a functional first version. From there, you can add database-backed conversations, retrieval from your own documents, authentication, streaming responses, analytics, and human handoff workflows. Start with a narrow use case, test realistic conversations, and expand only after the basic experience is secure and reliable.

Advertisement

Related Articles