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】header('Content-Type: application/json');の重要性

Posted at

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'); が必要な理由

  1. クライアント側が適切にレスポンスを処理できるようになる

    • $.ajax()dataType: "json" を設定している場合、レスポンスの Content-Typeapplication/json でないと、エラーになったり文字列として処理されたりする
  2. セキュリティの向上

    • ブラウザがレスポンスの内容を適切に解釈することで、不必要なコンテンツスニッフィング(Content Sniffing)が防げる
    • Content-Type を明示しないと、ブラウザが勝手にレスポンスを解釈し、意図しない挙動を引き起こす可能性がある

header() を忘れた場合の問題点

  • レスポンスが text/htmltext/plain として扱われ、JSONとしてパースされない
  • $.ajax()success コールバックで response.success にアクセスしようとしても undefined になる
  • デバッグがしづらくなり、エラー処理が煩雑になる
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?