0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPで作るサイト内チャット(OpenAI Responses API+サーバー中継)

Last updated at Posted at 2025-10-01

対象:WordPress/共用サーバ/さくら等で PHP が使える環境。音声や画像は後日拡張、まずはテキストのみに絞った最短ルートです。

ChatGPT(Plus)を埋め込むのではなく、OpenAIのAPIで自前UIを作ります。APIキーは必ずサーバー側で管理し、フロントからは呼ばせません。

はじめに

  • 本稿では Responses API を使います(Assistants APIの後継ライン)。
  • チャットの流れ:ブラウザ → あなたのPHP(中継) → OpenAI API → あなたのPHP → ブラウザ
  • ChatGPT Plus と API の請求は別です。APIは従量課金。PlusにAPI枠は付きません。
  • まずは OpenAI APIの無料クレジットが残っていれば課金なしでテスト可能(残高と有効期限はダッシュボードの Usage/Billing で確認)。

ディレクトリ例とファイル一式

  1. .env を 公開領域の外に配置(例:/home/username/.env)。権限は 600。
  2. 公開領域(例:public_html/php-chatgpt/)に以下を設置:
    ・index.php(フロントUI)
    ・api/chat.php(中継)
    ・デバッグ用に api/echo.php / post-test.html / api/test_openai.php(任意)
    ・公開領域に .env を置く場合のみ .htaccess で直リンク禁止(推奨は公開領域の外に置くこと)

.env(公開領域の外・権限600)

# /home/username/.env
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
OPENAI_MODEL=gpt-4.1-mini
ALLOWED_ORIGIN=*   # テスト中は *、本番は https://your-domain.example に限定

※ 共有サーバで読めない場合のみ 640 を試す。APIキーは絶対にフロントへ出さない。

index.php(最小チャットUI/相対パスで中継にPOST)

<!doctype html>
<meta charset="utf-8">
<title>Site Chat (PHP + Responses API)</title>
<style>
body{font-family:system-ui,sans-serif;margin:2rem} #log p{margin:.4rem 0}
#log p.user{color:#444} #log p.bot{color:#0a0}
textarea{width:100%;height:6rem} button{padding:.6rem 1rem}
</style>
<body>
<h1>サイト内チャット(PHP中継)</h1>
<textarea id="msg" placeholder="質問を入力…"></textarea><br>
<button id="send">送信</button>
<div id="log" aria-live="polite"></div>

<script>
const $msg=document.getElementById('msg'); const $log=document.getElementById('log');
document.getElementById('send').onclick = async () => {
const message = $msg.value.trim(); if(!message) return;
addLine('あなた: '+message, 'user'); $msg.value='';
try{
const r = await fetch('api/chat.php', { // 重要:先頭に / を付けない(相対パス)
  method:'POST',
  headers:{'Content-Type':'application/json'},
  body: JSON.stringify({message})
});
const data = await r.json();
addLine('AI: ' + (data.reply || data.error || '[no reply]'), 'bot');
}catch(e){ addLine('AI: [通信エラー]', 'bot'); }
};
function addLine(text, cls){ const p=document.createElement('p'); p.textContent=text; p.className=cls; $log.appendChild(p); window.scrollTo({top:document.body.scrollHeight,behavior:'smooth'}); }
</script>
</body>

api/chat.php(中継:JSONで統一+バックオフ付き)

※ loadEnv('/home/xxxxx/.../.env'); のパスはあなたの環境に合わせて変更。

詳しくはこちら>>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?