<?php
declare(strict_types=1);

$url = $argv[1] ?? null;
if (!$url) {
    fwrite(STDERR, "Usage: php scripts/dump_headers.php <url>\n");
    exit(2);
}

$ctx = stream_context_create([
    'http' => [
        'follow_location' => 0,
        'max_redirects' => 0,
        'timeout' => 3.0,
        'ignore_errors' => true,
        'method' => 'GET',
        'header' => "User-Agent: HeaderDump/1.0\r\nRange: bytes=0-0\r\n",
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
    ],
]);

$http_response_header = null;
set_error_handler(static function (int $severity, string $message): bool {
    fwrite(STDERR, "PHP warning captured: $message\n");
    return true;
});
$fp = @fopen($url, 'rb', false, $ctx);
restore_error_handler();
if ($fp !== false) {
    fclose($fp);
}

if (!isset($http_response_header) || !is_array($http_response_header)) {
    echo "(no headers)\n";
    exit(1);
}

foreach ($http_response_header as $h) {
    echo $h, "\n";
}

