How Can I Access Any HTTP Request Header in PHP?
Dec 14, 2024 pm 02:43 PMHow to Read Any Request Header in PHP
Problem:
How can you access any HTTP header, including custom headers, in PHP?
Answer:
There are several methods to read request headers in PHP, depending on your specific requirements:
Single Header Retrieval:
If you only need to retrieve a single header value, use the following syntax:
<?php // Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_') $headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX']; ?>
Apache Module or FastCGI (PHP 5.4 ):
If PHP is running as an Apache module or using FastCGI with PHP 5.4 or later, you can use the apache_request_headers() function:
<?php $headers = apache_request_headers(); foreach ($headers as $header => $value) { echo "$header: $value <br />\n"; } ?>
Fallback Method:
In all other cases, you can use the following userland implementation:
<?php function getRequestHeaders() { $headers = array(); 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"; } ?>
Additional Functions:
- getallheaders() (PHP 5.4 ): Alias of apache_request_headers().
- apache_response_headers(): Fetches all HTTP response headers.
- headers_list(): Fetches a list of headers to be sent.
The above is the detailed content of How Can I Access Any HTTP Request Header in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Simplified HTTP Response Mocking in Laravel Tests

Build a React App With a Laravel Back End: Part 2, React

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon
