How to Make PHP Friends with ChatGPT: Step-by-Step API Integration

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

Why Does a PHP Developer Need ChatGPT?

\n\n

Imagine: you’re writing a website in PHP, and suddenly you realize your user is missing a "smart" assistant. Not a simple chat with pre-written answers, but a real artificial intelligence that can write code, translate texts, generate ideas, or simply maintain a meaningful dialogue. Sounds like science fiction? Well, it’s not.

\n\n

Today, integrating the ChatGPT API in PHP is not rocket science, but a fairly routine task that any developer familiar with the basics of the language can master. And I’ll prove it to you.

\n\n

In this article, we won’t just copy a couple of lines from the documentation. We’ll figure out how to properly send requests, process responses, manage conversation context, and avoid crashing the server. Let’s go!

\n\n

What Do We Need to Get Started?

\n\n

Before writing code, let’s make sure you have everything you need:

\n\n
    \n
  • PHP 8.0+ — older versions may have issues with cURL and JSON.
  • \n
  • cURL extension — enable it in php.ini (usually enabled by default).
  • \n
  • OpenAI API key — register at platform.openai.com, go to the API keys section, and create a new secret key.
  • \n
  • A little patience — sometimes the API doesn’t respond immediately, especially for complex requests.
  • \n
\n\n

Important: keep your API key secure. Never insert it directly into code that might end up in a public repository. Use .env files or server environment variables.

\n\n

Writing Your First Request to ChatGPT in PHP

\n\n

Let’s start with the simplest thing: send a single message and get a response. This is the foundation on which all further work with the API is built.

\n\n
<?php\n// Configuration\n$apiKey = 'sk-your_super_secret_key';\n$url = 'https://api.openai.com/v1/chat/completions';\n\n// Request data\n$data = [\n    'model' => 'gpt-3.5-turbo', // can use gpt-4 if you have access\n    'messages' => [\n        [\n            'role' => 'user',\n            'content' => 'Tell me a joke about programmers in Russian'\n        ]\n    ],\n    'temperature' => 0.7, // higher means more creative response\n    'max_tokens' => 500   // maximum response length\n];\n\n// Initialize cURL\n$ch = curl_init($url);\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($data));\n\n// Send 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    $reply = $result['choices'][0]['message']['content'];\n    echo "ChatGPT says: " . $reply;\n} else {\n    echo "Error! HTTP code: " . $httpCode . "<br>";\n    echo "Server response: " . $response;\n}\n?>
\n\n

Did you run it? Congratulations, you’ve just written your first ChatGPT API integration in PHP! If everything is done correctly, you’ll see a funny joke from the neural network.

\n\n

Breaking Down the Code

\n\n

Let’s look at what’s happening here so you can easily adapt this code for your own tasks.

\n\n

Request Structure

\n\n

The OpenAI API expects a JSON with several required fields:

\n\n
    \n
  • model — which model will respond. gpt-3.5-turbo is the optimal choice for most tasks: fast and cheap. gpt-4 is smarter but more expensive and slower.
  • \n
  • messages — an array of messages. Each message has a role (system, user, assistant) and content (text).
  • \n
  • temp

Blogs

Book Recommendations