Skip to content

HTTP ヘッダを表示する PHP サンプルコード

Web のテストを行う場合、「サーバ側で HTTP リクエストがどう見えているか?」が分かると便利な場合があります。 「Web サーバのログを確認する」「パケットをキャプチャする」などの選択肢があると思いますが、いずれもやや面倒です。 こういった場合、もし PHP が使えるのであれば「PHP スクリプトで HTTP ヘッダを表示させる」という方法があります。 今回はそういったケースで使える PHP のサンプルスクリプトをメモしておきます。

WebUI 用

スクリプト

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      font-family: "Courier New", monospace;
    }

    table th {
      color: #fff;
      background: #000;
    }

    table td {
      background: #eee;
    }

    table tr:nth-child(odd) td {
      background: #fff;
    }
  </style>
  <title>
    <?php $_SERVER["REQUEST_URI"]; ?>
  </title>
</head>

<body>
  <table border="1">
    <tr>
      <th>Item</th>
      <th>Value</th>
    </tr>
    <?php
    $srcaddr = $_SERVER["REMOTE_ADDR"];
    echo "<tr align=\"left\"><td>Source IP Address</td><td>$srcaddr</td></tr>";

    $headers = getallheaders();
    ksort($headers);

    foreach ($headers as $name => $value) {
        echo "<tr align=\"left\"><td>$name</td><td>$value</td></tr>";
    }
    ?>
  </table>
</body>

</html>

表示結果

file

CLI 用

スクリプト

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
$srcaddr = $_SERVER['REMOTE_ADDR'];
echo "Source IP Address:$srcaddr\n";

$headers = getallheaders();
ksort($headers);

foreach ($headers as $name => $value) {
    echo "$name:$value\n";
}
?>

実行結果

% xh --print=hb https://example.com/sample.php
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
Date: Fri, 14 Mar 2025 15:16:49 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.62 (Amazon Linux)
Transfer-Encoding: chunked

Source IP Address:192.0.2.123
Accept:*/*
Accept-Encoding:gzip, deflate, br, zstd
Connection:keep-alive
Host:example.com
User-Agent:xh/0.24.0