How to read any request header in PHP?

Spread the love

Sometimes, we want to read any request header in PHP.

In this article, we’ll look at how to read any request header in PHP.

How to read any request header in PHP?

To read any request header in PHP, we can use the $_SERVER array.

For instance, we write

function get_request_headers()
{
    $headers = [];
    foreach ($_SERVER as $key => $value) {
        if (substr($key, 0, 5) != "HTTP_") {
            continue;
        }
        $header = str_replace(
            " ",
            "-",
            ucwords(str_replace("_", " ", strtolower(substr($key, 5))))
        );
        $headers[$header] = $value;
    }
    return $headers;
}

$headers = get_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}

to define the get_request_headers function.

In it, we loop through the $_SERVER array entries with a foreach loop.

In the loop, we check if the $key starts with 'HTTP_'.

If it does, then we put the entry in the $headers array.

The key for each entry is the $key string without the 'HTTP_' part.

Then we call get_request_headers to get an array of $headers and loop through the entries with the foreach loop.

Conclusion

To read any request header in PHP, we can use the $_SERVER array.

Leave a Reply

Your email address will not be published.