PHP and AI: How to Befriend ChatGPT with Your PHP Code

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

PHP and AI: The Revolution That Is Already Here

\n\n

Have you ever dreamed that your PHP website could write articles by itself, answer user questions, or help clients with tech support? In the past, this sounded like science fiction, but today it is a reality available to every developer. OpenAI's ChatGPT has opened new horizons for web development in PHP, and in this article, we will show you how to harness this power in your projects.

\n\n

Forget boring feedback forms and static FAQs. Imagine: a user visits your site, asks a question in natural language, and your PHP script sends a request to ChatGPT, receives a meaningful response, and displays it in real time. Or your blog automatically generates unique SEO-optimized texts. Sounds cool? Let's go!

\n\n

What Do You Need to Integrate ChatGPT into PHP?

\n\n

Before we start writing code, let's figure out the necessary tools. To work with ChatGPT via PHP, you will need:

\n\n
    \n
  • PHP 8.0+ (8.1 or higher recommended for better support)
  • \n
  • cURL (included in most PHP builds)
  • \n
  • OpenAI API key (can be obtained at platform.openai.com)
  • \n
  • Composer (optional, but simplifies library installation)
  • \n
\n\n

The main advantage of PHP is that you don't need complex frameworks — basic functionality can be implemented with just a few dozen lines of code. And yes, PHP and ChatGPT work great together, despite many considering this language outdated.

\n\n

Basic Connection to the OpenAI API in PHP

\n\n

Let's start with the simplest thing — sending a request to ChatGPT and receiving a response. Here is a minimal working example in pure PHP:

\n\n
<?php\n// Configuration\n$apiKey = 'sk-your-api-key-here';\n$apiUrl = 'https://api.openai.com/v1/chat/completions';\n\n// Request data\n$requestData = [\n    'model' => 'gpt-3.5-turbo',\n    'messages' => [\n        [\n            'role' => 'system',\n            'content' => 'You are a helpful assistant who helps users.'\n        ],\n        [\n            'role' => 'user',\n            'content' => 'Tell me in a few words about PHP and AI.'\n        ]\n    ],\n    'max_tokens' => 200,\n    'temperature' => 0.7\n];\n\n// Initialize cURL\n$ch = curl_init($apiUrl);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_POST, true);\ncurl_setopt($ch, CURLOPT_HTTPHEADER, [\n    'Content-Type: application/json',\n    'Authorization: Bearer ' . $apiKey\n]);\ncurl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));\n\n// Execute request\n$response = curl_exec($ch);\n$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);\ncurl_close($ch);\n\n// Process response\nif ($httpCode === 200) {\n    $result = json_decode($response, true);\n    $answer = $result['choices'][0]['message']['content'];\n    echo "ChatGPT response: " . $answer;\n} else {\n    echo "Error: HTTP " . $httpCode;\n}\n?>
\n\n

This code sends a request to the GPT-3.5 Turbo model and outputs the response. Pay attention to the temperature parameter — it controls the creativity of responses (0 — strict facts, 1 — maximum imagination).

\n\n

Improving the Code with a Library

\n\n

If you use Composer, I recommend installing the official OpenAI PHP library:

\n\n
composer require openai-php/client
\n\n

Example with the library:

\n\n
<?php\nrequire 'vendor/autoload.php';\n\n$client = OpenAI::client('sk-your-api-key-here');\n\n$response = $client->chat()->create([\n    'model' => 'gpt-3.5-turbo',\n    'messages' => [\n        ['role' => 'system', 'content' => 'You are a PHP expert.'],\n        ['role' => 'user', 'content' => 'How to use ChatGPT in PHP?']\n    ],\n]);\n\necho $response->choices[0]->message->content;\n?>
\n\n

Code with

Blogs

Book Recommendations