Introduction to using ChatGPT in PHP

USING-CHATGPT-IN-PHP-1 Introduction to using ChatGPT in PHP

Find out how to make use of ChatGPT in PHP and have natural language conversations and generate consistent responses.

Learn how to make use of ChatGPT in PHP to have natural language conversations and generate consistent responses. We show you how to make requests to this artificial intelligence program and how to authenticate with the OpenAI API.

According to his own ChatGPT, ChatGPT is a language model developed by OpenAI based on the GPT architecture. GPT stands for “Generative Pre-trained Transformer”, which translates as “Generative Pre-trained Transformer”. It is a type of artificial intelligence model designed to understand and generate text in a coherent and contextual way.

chatgpt-1-1024x725 Introduction to using ChatGPT in PHP
Capture of one of the queries to ChatGPT, from the system console

Both the previous definition and the following introduction were obtained by writing the question What is ChatGPT? in the console (see image that precedes these lines -in spanish-).

In essence, ChatGPT is an artificial intelligence program capable of having natural language conversations with users. You have been trained on a wide variety of texts and can generate coherent and relevant responses based on the prompts and questions you receive. ChatGPT can be used in a wide range of applications, such as customer support, content generation, answering questions, and many other tasks that involve human language interaction.

It is important to note that while ChatGPT is very advanced and can generate responses that seem natural, it does not have any real understanding or knowledge. Your responses are based on patterns learned during your training in large amounts of text, but you have no real understanding of the world or concepts beyond those patterns.

Part of ChatGPT’s answer to the question What is ChatGPT?

ChatGPT Models

Currently, you can work with ChatGPT by registering free of charge at Your free ChatGPT account will allow you to operate, at the console level (by writing the questions yourself), with GPT-3.5, the restricted model but with all the capabilities enabled to help you on a day-to-day basis. The GPT-4 model is more advanced but it is paid.

There are two types of subscription to use the ChatGPT console:

  • Free plan. Access to the GPT-3.5 model, standard response speed, and model update at normal rate.
  • ChatGPT Plus paid plan ($20/month). Access to GTP-4, high response speed and exclusive access to beta features.
  • For more information, go to the official documentation, Models section.


Beyond working with ChatGPT, through its console, writing the questions ourselves, it is possible to operate with the system through an API Key. The goal is to make use of ChatGPT in PHP or any other programming language.

An application programming interface (API) key is a unique identifier that is used to authenticate and authorize to a user, developer or program calling a API.

To use the ChatGPT API, each OpenAI account has a number of free credits, but once that amount is exceeded, the balance must be charged to be able to use it. In this page you can add money to the credit balance or cancel the plan. And This other, find a summary of your API usage.

You can interact with the ChatGPT API via HTTP requests from any programming language, via the official Python links, the official Node.js library or a community maintained library. More information here and here.

Interact with the ChatGPT API from PHP

Among these programming languages, there is PHP and I will describe an example of use below.

The ChatGPT API allows you to interact with the GPT-3.5 language model, like the one you can experience via the console by writing the questions yourself, through API calls. Here is a basic guide on how to use it from PHP:

  1. API access. Before you begin, you need access to the GPT-3.5 API. You need an API key provided by OpenAI to use its services. If you don’t have an OpenAI account yet, go to official Web site and sign up. Then, access your control panel and in the account management, go to the API Keys section to create a new key.
  2. Making an API Request Once you have access to the API, you can make API calls to get responses from the model. Requests are made via HTTP POST.

Suppose we want to make a request to the ChatGPT API to tell us a joke, using PHP and the functioncurl. The code would be something similar to the following:

$api_key = "YOUR_API_KEY";
$url = "";
$headers = array(
    "Content-Type: application/json",
    "Authorization: Bearer $api_key"
$data = array(
    "model" => "gpt-3.5-turbo",
    "messages" => array(
        array("role" => "system", "content" => "You are an assistant who speaks English."),
        array("role" => "user", "content" => "Tell me a joke.")
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$result = json_decode($response, true);
echo $result['choices'][0]['message']['content'];

Be sure to replace”YOUR_API_KEY” with your API key provided by OpenAI. This code makes an HTTP POST request to the ChatGPT API, and then processes the JSON response to display the content of the attendee’s message in the chat.

Remember to check the official OpenAI documentation for up-to-date information on using the API, as technical details might change over time.

What is “Bearer”?

“Bearer” is a type of access token used in HTTP authentication to identify and authorize users or applications making requests to a web service. In the context of the OpenAI API (and many other services), “Bearer” is used to authenticate your API requests.

When you make a request to an API that requires authentication using an access token, you should typically include the token in the HTTP request header. The authentication header looks like this:

Authorization: Bearer <YOUR_ACCESS_TOKEN>

In this case,<YOUR_ACCESS_TOKEN> is the token you got when you registered with the service and created an API key. By including this header in your request, you are providing a secure way to identify yourself to the service and gain authorized access.

Using “Bearer” tokens is a common practice in online authentication, as it is a secure way to convey authentication information without exposing it directly in the URL or request body.

In the example I provided above, by using the “Authorization: Bearer” header in API requests, you are sending your API key as an access token to authenticate with the OpenAI API and get responses from the model.

Should cURL be installed on the server?

Yes, in order to use the functioncurl in PHP and make HTTP requests, you need to have the cURL extension enabled on your server. Most PHP servers come with cURL pre-installed and enabled by default, but in some cases it might be necessary to manually enable it.

If you’re not sure if cURL is enabled on your server, you can verify it by running the following code in a PHP file and accessing that file in your browser:

if (function_exists('curl_version')) {
    echo "cURL is enabled on this server.<br /><br />";
} else {
    echo "cURL is not enabled on this server.<br /><br />";

If you see the message “cURL is enabled on this server.”, it means that cURL is available and you can use it in your PHP scripts. If you see the message “cURL is not enabled on this server.”, you will need to enable it by following the instructions provided by your hosting provider or system administrator.

In case you are unable to enable cURL on your server, you may also consider using alternative libraries for making HTTP requests, such asfile_get_contents() or external libraries like Guzzle. However, cURL is one of the most common and versatile options for making HTTP requests in PHP.

Is the Composer dependency manager needed?

No you don’t need Composer specifically to use the function cURL in PHP and make HTTP requests.

Composer is a dependency management tool for PHP that is mainly used to manage the libraries and packages that are used in larger PHP projects. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

The functioncurl It is part of the PHP core and is used to make HTTP requests without the need to install additional packages. If you’re only interested in making basic HTTP requests using cURL in PHP, you don’t need Composer for that purpose.

However, if you are working on a larger PHP project and want to use external libraries to handle HTTP requests in a more advanced way, you might consider using Composer to manage those dependencies. Composer makes it easy to install and update external libraries and packages in your project.

In short, if you only need to use the functioncurl to make basic HTTP requests in PHP, you don’t need Composer. But if you’re planning to build a more complex project that involves a lot of external dependencies, Composer could be useful for managing those dependencies efficiently.

How to show possible errors in API response?

The statement that you can use to display possible errors in the API response using the function curl_error() is:

$response = curl_exec($ch);

if ($response === false) {
    echo "Request failed: " . curl_error($ch);
} else {
    //echo $response;


Tell me a joke

The little PHP program I’ve developed in this article accesses ChatGPT via an API key, so it tells us a joke.

Of course, you can add at the beginning of the code, the following instruction:

echo "ChatGPT, tell me a joke<br /><br />";

Once implemented on your server, you can run it from the address bar of your browser, getting jokes (so bad) like the following 馃槈 -in spanish- :

chatgpt-2-1024x404 Introduction to using ChatGPT in PHP
Capture of an output of the execution, in spanish, of the PHP program that interacts with ChatGPT


Serve this article as an introduction to the use of ChatGPT in PHP. After reading it, you will have discovered how this artificial intelligence program can hold conversations in natural language and generate coherent responses, executing a PHP script from your own server.

The example shown is very simple and its only purpose is to show how to interact with ChatGPT from a program, written in PHP language.

Check out the different subscription plans to get the most out of ChatGPT’s capabilities and the official documentation. If you run the code shown in this article, be sure to make the changes for your server and use a sandbox environment. You will need to authenticate with the OpenAI API for which you must obtain an API key in your account.

Comparte en Mastodon

Icono de Mastodon





Likes, Bookmarks, and Reposts


Leave a Reply

Your email address will not be published. Required fields are marked *

Informaci贸n b谩sica sobre protecci贸n de datos Ver m谩s

  • Responsable: Antonio Cambronero.
  • Finalidad:  Moderar los comentarios.
  • Legitimaci贸n:  Por consentimiento del interesado.
  • Destinatarios y encargados de tratamiento: No se ceden o comunican datos a terceros para prestar este servicio. El Titular ha contratado los servicios de alojamiento web a GreenGeeks que act煤a como encargado de tratamiento.
  • Derechos: Acceder, rectificar y suprimir los datos.
  • Informaci贸n Adicional: Puede consultar la informaci贸n detallada en la Pol铆tica de Privacidad.

This site uses Akismet to reduce spam. Learn how your comment data is processed.