{"id":16271473,"url":"https://github.com/rkrehn/phpchatgpt","last_synced_at":"2025-04-08T15:30:27.720Z","repository":{"id":217592875,"uuid":"744296537","full_name":"rkrehn/phpchatgpt","owner":"rkrehn","description":"How to use ChatGPT with PHP","archived":false,"fork":false,"pushed_at":"2024-01-17T02:46:30.000Z","size":4,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-14T11:52:58.083Z","etag":null,"topics":["chatgpt","chatgpt-api","chatgpt-app","php","php7","php8","tutorial","tutorial-code"],"latest_commit_sha":null,"homepage":"https://www.krehnsolutions.com","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rkrehn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-17T02:13:35.000Z","updated_at":"2024-01-17T02:48:14.000Z","dependencies_parsed_at":null,"dependency_job_id":"53fb87e1-0baa-40aa-9ed4-725e1d59d30f","html_url":"https://github.com/rkrehn/phpchatgpt","commit_stats":null,"previous_names":["rkrehn/phpchatgpt"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fphpchatgpt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fphpchatgpt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fphpchatgpt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fphpchatgpt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rkrehn","download_url":"https://codeload.github.com/rkrehn/phpchatgpt/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247870825,"owners_count":21009938,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chatgpt","chatgpt-api","chatgpt-app","php","php7","php8","tutorial","tutorial-code"],"created_at":"2024-10-10T18:13:38.124Z","updated_at":"2025-04-08T15:30:27.674Z","avatar_url":"https://github.com/rkrehn.png","language":null,"readme":"# About\nThis guide is designed to teach people how to use ChatGPT using a basic \"I want one response\" in PHP. This code is used in my travel itinerary generation website [ReisPlan](https://www.reisplan.net) and built off my [C# tutorial](https://github.com/rkrehn/csharpchatgpt). I love how PHP handles JSON and XML data, so this tutorial is a bit easier.\n\n# Setup\n\nDeclare your API key (insert your [OpenAI API key](https://platform.openai.com/account/api-keys) in the quotes)\n\n```PHP\n// API endpoint URL\n$url = 'https://api.openai.com/v1/chat/completions';\n\n// Your OpenAI API key\n$apiKey = '[API KEY]';\n```\n\n# Setting up the request\n\nThe following code creates the JSON request to OpenAI. You can review all the options you can include here: [https://platform.openai.com/docs/api-reference/chat/create](https://platform.openai.com/docs/api-reference/chat/create).\n\nIt's worth noting that only the \"model\" and the \"messages\" are required in the body. There are [many models](https://platform.openai.com/docs/models), but I'm using **gpt-3.5-turbo** in this example. Likewise, there are a few roles you can use such as system, user, assistance, or function. Typically, the **system** role defines what you want to accomplish. In our example, we'll tell ChatGPT **sytem** role that is acting as a travel agent (used on my [ReisPlan](https://www.reisplan.net) site).\n\nFirst, we prepare the prompt statement:\n\n```PHP\n  // Prompt for the conversation\n  $messages = array(\n      array('role' =\u003e 'system', 'content' =\u003e 'You are a travel advisor that will deliver a detailed itinerary based on the information provided by the user.'),\n      array('role' =\u003e 'user', 'content' =\u003e 'I am traveling to Denver for 7 days. Things I\\'m interested in include museums and hiking.')\n  );\n```\n\nNext, we build a JSON array. In the below scenario, I'm only sending the prompt and the model using an **array** and then encoding it into JSON data using the **json_encode** function.\n\n```PHP\n// Convert messages to JSON\n$postData = array(\n    'messages' =\u003e $messages,\n    'model' =\u003e 'gpt-3.5-turbo'  // Specify the model here\n);\n\n$jsonData = json_encode($postData);\n```\n\nNext, we set up the headers using an **array** to send the request using the Authorization header with our API Key and JSON content type. The **$options** array will set up the header, method (POST), and content using the **$jsonData** we built above. \n\n```PHP\n// Set headers for the API request\n$headers = array(\n    'Content-Type: application/json',\n    'Authorization: Bearer ' . $apiKey\n);\n\n$options = array(\n    'http' =\u003e array(\n        'header'  =\u003e implode(\"\\r\\n\", $headers),\n        'method'  =\u003e 'POST',\n        'content' =\u003e $jsonData\n    )\n);\n```\n\nThe **stream_context_create** function will create the send data to OpenAI using an HTTP request.\n\n```PHP\n$context = stream_context_create($options);\n```\n\nFinally, we'll execute the API request using **file_get_contents** function and check for errors.\n\n```PHP\n// Execute the API request\n$response = file_get_contents($url, false, $context);\n\n// Check for errors\nif ($response === false) {\n    $error = error_get_last()['message'];\n    echo 'API request failed: ' . $error;\n    exit;\n}\n```\n\n# Receiving the response\n\nWe'll just the **json_decode** function to read the $response variable from OpenAI.\n\n```PHP\n// Decode the API response\n$data = json_decode($response, true);\n```\nYou will receive a JSON response like this in the **$data** variable (don't copy this):\n\n```JSON\n{\n  \"id\": \"chatcmpl-123\",\n  \"object\": \"chat.completion\",\n  \"created\": 1677652288,\n  \"model\": \"gpt-3.5-turbo-0613\",\n  \"choices\": [{\n    \"index\": 0,\n    \"message\": {\n      \"role\": \"assistant\",\n      \"content\": \"\\n\\nSure, I can recommend you check out Livin the Dream brewery in Littleton and Denver Beer Co in Englewood.\",\n    },\n    \"finish_reason\": \"stop\"\n  }],\n  \"usage\": {\n    \"prompt_tokens\": 9,\n    \"completion_tokens\": 12,\n    \"total_tokens\": 21\n  }\n}\n```\n\n* choices[0] is the first response\n* message is the node within the choices[0]\n* content is the response you're looking for\n\nNext, we'll extract the **$data** using the above and then explode individual lines in the response. The **$reply** variable contains the whole response.\n\nBut, I used **$lines** to break the reply response so I could get multiple lines of data and have them display on the website.\n\n```PHP\n// Extract the assistant's reply\n$reply = $data['choices'][0]['message']['content'];\n\n// Output the reply\n// Assuming $reply contains the response from the API\n$lines = explode(\"\\n\", $reply);\n```\n\nThe following loop examines each **$line** received and displays it on the website using the echo function.\n\n```PHP\n// Loop through the lines\n$previousLineEmpty = false;\nforeach ($lines as $line) {\n    // Process each line as needed\n    if (empty($line)) {\n        $previousLineEmpty = true;\n    } else {\n        if ($previousLineEmpty) {\n            echo \"\u003cbr\u003e\u003cstrong\u003e\" . $line . \"\u003c/strong\u003e\u003cbr\u003e\"; // Output the line in bold\n            $previousLineEmpty = false;\n        } else {\n            echo $line . \"\u003cbr\u003e\"; // Output each line\n        }\n    }\n}\n```\n\n\n# Everything together\n\nNow, put it together in all its glory:\n\n```PHP\n// API endpoint URL\n$url = 'https://api.openai.com/v1/chat/completions';\n\n// Your OpenAI API key\n$apiKey = '[API KEY]';\n\n// Prompt for the conversation\n$messages = array(\n    array('role' =\u003e 'system', 'content' =\u003e 'You are a travel advisor that will deliver a detailed itinerary based on the information provided the user.'),\n    array('role' =\u003e 'user', 'content' =\u003e 'I am traveling to Denver for 7. Things I\\'m interested in include breweries.')\n);\n\n// Convert messages to JSON\n$postData = array(\n    'messages' =\u003e $messages,\n    'model' =\u003e 'gpt-3.5-turbo'  // Specify the model here\n);\n\n$jsonData = json_encode($postData);\n\n// Set headers for the API request\n$headers = array(\n    'Content-Type: application/json',\n    'Authorization: Bearer ' . $apiKey\n);\n\n$options = array(\n    'http' =\u003e array(\n        'header'  =\u003e implode(\"\\r\\n\", $headers),\n        'method'  =\u003e 'POST',\n        'content' =\u003e $jsonData\n    )\n);\n\n$context = stream_context_create($options);\n\n// Execute the API request\n$response = file_get_contents($url, false, $context);\n\n// Check for errors\nif ($response === false) {\n    $error = error_get_last()['message'];\n    echo 'API request failed: ' . $error;\n    exit;\n}\n\n// Decode the API response\n$data = json_decode($response, true);\n\n// Extract the assistant's reply\n$reply = $data['choices'][0]['message']['content'];\n```\n\n\u003e Sure, I can recommend you check out Livin the Dream brewery in Littleton and Denver Beer Co in Englewood.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkrehn%2Fphpchatgpt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frkrehn%2Fphpchatgpt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkrehn%2Fphpchatgpt/lists"}