header('Content-Type: application/json');
の重要性
Web開発でAPIを作成する際、PHPの header('Content-Type: application/json');
を適切に設定することは非常に重要。この設定をしないと、クライアント側のJavaScript(特に $.ajax()
や fetch()
などのAPI呼び出し)が正しく動作しない場合がある。
サンプルコード
sample.php
session_start();
header('Content-Type: application/json');
if (empty($_POST['id']) || empty($_POST['password'])) {
echo json_encode(["success" => false, "message" => "IDとパスワードを入力してください"]);
exit;
}
//仮の認証処理
if ($_POST['id'] === 'admin' && $_POST['password'] === 'pass') {
echo json_encode(["success" => true]);
} else {
echo json_encode(["success" => false, "message" => "認証に失敗しました"]);
}
//ほかの処理
//......
sample.js
$(document).ready(function(){
$("#login-form").submit(function(event){
event.preventDefault();
let id = $("#id").val();
let password = $("#password").val();
$.ajax({
url: "sample.php",
type: "POST",
data: { id: id, password: password },
dataType: "json",
success: function(response) {
if (response.success) {
window.location.href = "settings.php";
} else {
$("#error").text(response.message);
}
},
error: function(xhr, status, error) {
console.log("AJAXエラー: ", xhr, status, error);
$("#error").text("通信エラーが発生しました");
}
});
});
});
header('Content-Type: application/json');
が必要な理由
-
クライアント側が適切にレスポンスを処理できるようになる
-
$.ajax()
のdataType: "json"
を設定している場合、レスポンスのContent-Type
がapplication/json
でないと、エラーになったり文字列として処理されたりする
-
-
セキュリティの向上
- ブラウザがレスポンスの内容を適切に解釈することで、不必要なコンテンツスニッフィング(Content Sniffing)が防げる
-
Content-Type
を明示しないと、ブラウザが勝手にレスポンスを解釈し、意図しない挙動を引き起こす可能性がある
header()
を忘れた場合の問題点
- レスポンスが
text/html
やtext/plain
として扱われ、JSONとしてパースされない -
$.ajax()
のsuccess
コールバックでresponse.success
にアクセスしようとしてもundefined
になる - デバッグがしづらくなり、エラー処理が煩雑になる