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 getRequestHeaders()
{
    $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 = getRequestHeaders();

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

to create the getRequestHeaders function that loops through the $_SERVER associative array with a foreach loop.

We get the header key with $key and the header value with $value.

Conclusion

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

Leave a Reply

Your email address will not be published. Required fields are marked *