How to Read Any Request Header in PHP

How do I read any request header in PHP

IF: you only need a single header, instead of all headers, the quickest method is:

<?php
// Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_')
$headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX'];



ELSE IF: you run PHP as an Apache module or, as of PHP 5.4, using FastCGI (simple method):

apache_request_headers()

<?php
$headers = apache_request_headers();

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



ELSE: In any other case, you can use (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";
}



See Also:

getallheaders() - (PHP >= 5.4) cross platform edition Alias of apache_request_headers()
apache_response_headers() - Fetch all HTTP response headers.

headers_list() - Fetch a list of headers to be sent.

How to read the php request header values?

From your screenshot (which appears to be from a browser's Network tool) it looks like you are talking about reading the header values which were received by the PHP script from the request your browser sent to PHP. That's nothing to do with cURL - cURL is for sending HTTP requests from your PHP script to another URL...it's unrelated to the interaction between the client-side and PHP via your webserver.

To read the headers which are incoming into your PHP script from the browser (or other client) making the request, you can use getallheaders() which returns an associative array of all the received headers.

e.g. to simply list them all:

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

Documentation: https://www.php.net/manual/en/function.getallheaders.php

Get custom request header

$headers = getallheaders();  
$message = $headers['api_key'];

Read request header before reading entire body of POST request in PHP

I think it is better to solve this problem even before the file hits the backend server. On the proxy level, for nginx, you can use client_max_body_size



Related Topics



Leave a reply



Submit