対象: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 で確認)。
ディレクトリ例とファイル一式
- .env を 公開領域の外に配置(例:/home/username/.env)。権限は 600。
- 公開領域(例: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>