実現したいこと・エラーの概要
PHPでAPIを作成しています。
PHP
1<?php 2.....略..... 3$body = file_get_contents("php://input"); 4$contents = json_decode($body, true); 5.....略.....
等の処理をしたいです。
開発環境では問題ありませんでしたが、本番環境では上手くできませんでした。
検証して以下の部分が上手く動かないことがわかりました。
通常の文字の送信は問題ありませんが、<script />
タグが送されるとエラーが出ます。
逆に<script />
以外のタグは調べた範囲ではエラーは出ません。
サーバー側での記述
php
1<?php 2header('Content-Type: application/json; charset=UTF-8'); 3header("Access-Control-Allow-Origin: *"); 4header("Access-Control-Allow-Headers: X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept"); 5header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH, HEAD");
htaccess
1Header set Access-Control-Allow-Origin "*" 2Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
呼び出し側
成功時(エラーが出ない時の一例)
javascript
1$.post("https://api.example.com/", 2 { 3 test: "<scrdsdipt />" 4 } 5);
{test: "msg"}や{test: "<br />"}等も問題なく通ります
Headers(一般)
1リクエスト URL: https://api.example.com/ 2リクエスト メソッド: POST 3ステータス コード: 200 4リモート アドレス: ***.***.***.*** 5参照ポリシー: strict-origin-when-cross-origin
Response_Headers
1accept-ranges: none 2access-control-allow-headers: X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept 3access-control-allow-methods: GET, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH, HEAD 4access-control-allow-origin: * 5content-length: 0 6content-type: application/json; charset=UTF-8 7date: Sat, 12 Feb 2022 09:31:01 GMT 8server: Apache 9vary: Range 10x-powered-by: PHP/8.0.15
失敗するとき
javascript
1$.post("https://api.example.com", 2 { 3 test: "<script />" 4 } 5);
{test: "<script>"}や{test: "<script>alert('test')</script>"}等も同様にエラー
Headers(一般)
1リクエスト URL: https://api.example.com/ 2リクエスト メソッド: POST 3ステータス コード: 403 4参照ポリシー: strict-origin-when-cross-origin
Response_Headers
1accept-ranges: bytes 2content-length: 1509 3content-type: text/html 4date: Sat, 12 Feb 2022 09:31:04 GMT 5last-modified: Tue, 25 Jan 2022 07:27:32 GMT 6server: Apache
Request Headersは失敗時、成功時共通です
Request_Headers
1:authority: api.example.com 2:method: POST 3:path: / 4:scheme: https 5accept: */* 6accept-encoding: gzip, deflate, br 7content-length: 17 8content-type: application/x-www-form-urlencoded; charset=UTF-8 9origin: https://example.com 10referer: https://example.com/ 11sec-fetch-dest: empty 12sec-fetch-mode: cors 13sec-fetch-site: same-site 14user-agent: Mozilla/5.0 .......
補足情報
開発環境ではhtaccessを記述しなくても問題なくできました。
ご教授よろしくお願いいたします
追記
エラー時のブラウザの開発ツールのコンソール
javascript
1Access to XMLHttpRequest at 'https://api.example.com/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 2jquery-3.6.0.min.js:2 POST https://api.example.com/ net::ERR_FAILED 403
回答1件
あなたの回答
tips
プレビュー