Skip to content

HTTPヘッダ・クエリ文字列を表示するPHPサンプルコード

以前にHTTPヘッダを表示するPHPサンプルコードというメモを書きました。左記のメモに加え、「HTTPクエリ文字列も表示する」ように修正したサンプルコードをメモしておきます。

検証環境

対象 バージョン
Amazon Linux 2023.7.20250609
PHP 8.4

Apache&PHPのインストール

ApacheとPHPをインストールする場合、以下のように実行します。必要であればモジュールを追加します。他にはPHPのDockerコンテナを使う方法などもあろうかと思います。

Amazon Linux 2023

dnf -y install httpd php8.4 php8.4-fpm

Ubuntu 24.04 LTS

apt install -y  apache2 php8.3 php8.3-fpm
a2enmod proxy_fcgi setenvif
a2enconf php8.3-fpm
systemctl restart php8.3-fpm apache2

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
49
50
51
52
53
54
55
56
57
58
59
<!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>
  <h1>HTTP Request Headers</h1>
  <table border="1">
    <tr>
      <th>Header</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) {
        $v = htmlspecialchars($value);
        echo "<tr align=\"left\"><td>$name</td><td>$v</td></tr>";
    }
    ?>
  </table>

  <h1>Query Parameters</h1>
  <table border="1">
    <tr>
      <th>Item</th>
      <th>Value</th>
    </tr>
    <?php foreach ($_GET as $key => $value) {
        $v = htmlspecialchars($value);
        echo "<tr align=\"left\"><td>$key</td><td>$v</td></tr>";
    } ?>
  </table>
</body>

</html>

実行例

http://10.0.0.1/sample.php?flag1=true&flag2=false のようにクエリ文字列を指定してアクセスすると以下のように表示されます。

image

CLI 用

サンプルスクリプト

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

echo "HTTP Headers:\n";
$headers = getallheaders();
ksort($headers);

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

echo "Query Parameters:\n";

foreach ($_GET as $key => $value) {
    echo " " . $key . " = " . htmlspecialchars($value) . "\n";
}
?>

実行例

% xh --print=hb "http://10.0.0.1/sample.php?flag1=true&flag2=false"
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 189
Content-Type: text/html; charset=UTF-8
Date: Wed, 18 Jun 2025 22:46:53 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.58 (Ubuntu)
Vary: Accept-Encoding

Source IP Address:192.168.0.1
HTTP Headers:
 Accept:*/*
 Accept-Encoding:gzip, deflate, br, zstd
 Connection:keep-alive
 Host:10.0.0.1
 User-Agent:xh/0.24.1
Query Parameters:
 flag1 = true
 flag2 = false