- PHP Fetch all HTTP request headers
- What is HTTP / Use of HTTP?
- PHP apache_request_headers() Function
- Example
- Fetch all HTTP request headers
- Fetches all HTTP request headers from the current request.
- HTTP – get(RESPONSE) and set(REQUEST) custom HTTP headers using PHP ()
- Reading the custom header(Server side)
- Custom Headers with PHP
- and Now try to this in the http_request.php:
- Related posts:
- apache_request_headers
- Parameters
- Return Values
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 6 notes
PHP Fetch all HTTP request headers
Today, We want to share with you PHP Fetch all HTTP request headers.
In this post we will show you Fetch all HTTP request headers, hear for we will give you demo and example for implement.
In this post, we will learn about Fetches all the headers sent by the server in response to a HTTP request with an example.
What is HTTP / Use of HTTP?
“HTTP is the protocol(rules) (the set of ‘rules’) for (client side to server side)transferring data (e.g. HTML in web pages,form data,document, pictures, files) between (both of side) web servers and client browsers data transfer, and usually should takes place on port 80 generally used.
This is a most where the ‘http://’ in website(server side) URLs comes from.”
PHP apache_request_headers() Function
“This function is used to all retrive information data in Apache as a module then the headers(data) the browser send(client side) can be retrieved using(server side) the apache_request_headers() function”
Example
Request print_r( apache_request_headers() ); RESPONSE Array ( [Host] => www.pakainfo.com //host name [Connection] => keep-alive [User-Agent] => Mozilla/10.0 (Windows; U; syWindows NT 6.1; en-US) Apple_WebKit/532.0 (KHTML, like Gecko) Chrome/5.0.209.1 Safari/632.0 //get cache-control browser [Cache-Control] => max-age=1 //cach control [Accept] => application/xml,application/xhtml+xml+xhtml,text/html;q=0.5,text/plain;q=0.9,image/png,*/*;q=0.6 [Accept-Encoding] => gzip,deflate,sdch //support [Accept-Language] => en-US,en;q=0.8 //defult language [Accept-Charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3 //set char )
Fetch all HTTP request headers
Fetches all HTTP request headers from the current request.
// all http headers store in this varible $headers_data = apache_request_headers(); //get one by one header foreach ($headers_data as $header_info => $value_header)
HTTP – get(RESPONSE) and set(REQUEST) custom HTTP headers using PHP ()
First of all let us start by sending(browser to server) a custom HTTP header(data) to the server. and then I will be using cURL(HTTP request) library to send HTTP requests(On server).
Sending The Request Header(Client side to server side )
first Let’s say our custom(static) header name is Example like (‘Authorization’) and we want to set(static value) its value to ‘123456’,
now create a file named send_http-request_data.php with the following content:
$uri_senddata = 'http://localhost/request_http.php'; $ch_data = curl_init($uri_senddata); curl_setopt_array($ch_data, array( CURLOPT_HTTPHEADER => array('Authorization: [email protected]'), CURLOPT_RETURNTRANSFER =>true,//boolean true or false CURLOPT_VERBOSE => 1 )); //output display $out_data = curl_exec($ch_data); //curl close curl_close($ch_data); // echo response output echo $out_data;
Now we have sent(client to server) the request with method POST(secure).
The CURLOPT_VERBOSE option is used for debugging (debugging option 1,2,3.etc..)
when you want to output the (client side)request headers and (server side)the response headers.
and Now You all shall remove it on production.
Reading the custom header(Server side)
Now let’s make the reads that (make specific)custom header sent(client side data) from the curl request(and error and success message show).
and then create a file named http_request.php with the following contents and get all data.
print_r(apache_request_headers());
Custom Headers with PHP
To work around this we will have to (PHP run script)play around with the .htaccess but (set htaccess)you will need mod_rewrite.
setting htaccess file RewriteEngine On RewriteRule .? - [E=Authorization:%]
and Now try to this in the http_request.php:
echo "Server message = ".$_SERVER['Authorization'];
We hope you get an idea about PHP Fetch all HTTP request headers
We would like to have feedback on my Information blog .
Your valuable any feedback, Good question, Inspirational Quotes, or Motivational comments about this article are always welcome.
If you liked this post, Please don’t forget to share this as Well as Like FaceBook Page.
We hope This Post can help you…….Good Luck!.
Related posts:
apache_request_headers
Fetches all HTTP request headers from the current request. Works in the Apache, FastCGI, CLI, and FPM webservers.
Parameters
This function has no parameters.
Return Values
An associative array of all the HTTP headers in the current request, or false on failure.
Changelog
Version | Description |
---|---|
7.3.0 | This function became available in the FPM SAPI. |
Examples
Example #1 apache_request_headers() example
foreach ( $headers as $header => $value ) echo » $header : $value
\n» ;
>
?>
The above example will output something similar to:
Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 Host: www.example.com Connection: Keep-Alive
Notes
Note:
You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.
See Also
User Contributed Notes 6 notes
I didn’t found a replacement for apache_request_headers() in PHP::Compat (http://pear.php.net/package/PHP_Compat) so I wrote my own:
if( ! function_exists ( ‘apache_request_headers’ ) ) ///
function apache_request_headers () $arh = array();
$rx_http = ‘/\AHTTP_/’ ;
foreach( $_SERVER as $key => $val ) if( preg_match ( $rx_http , $key ) ) $arh_key = preg_replace ( $rx_http , » , $key );
$rx_matches = array();
// do some nasty string manipulations to restore the original letter case
// this should work in most cases
$rx_matches = explode ( ‘_’ , $arh_key );
if( count ( $rx_matches ) > 0 and strlen ( $arh_key ) > 2 ) foreach( $rx_matches as $ak_key => $ak_val ) $rx_matches [ $ak_key ] = ucfirst ( $ak_val );
$arh_key = implode ( ‘-‘ , $rx_matches );
>
$arh [ $arh_key ] = $val ;
>
>
return( $arh );
>
///
>
///
?>
Although we expect to see headers in mixed case, the standard RFC2616 demands that «field names are case-insensitive». PHP delivers the headers exactly untouched in whatever way the client sent them. Potentially you should expect to get any type of uppercase or lowercase or mixed.
Thus, if you want to be standards compliant, you must loop through every key and check it in a case-insensitive manner, instead of doing the obvious thing and using the name of the header as an array index.
There is a simple way to get request headers from Apache even on PHP running as a CGI. As far as I know, it’s the only way to get the headers «If-Modified-Since» and «If-None-Match» when apache_request_headers() isn’t available. You need mod_rewrite, which most web hosts seem to have enabled. Put this in an .htacess file in your web root:
RewriteEngine on
RewriteRule .* — [E=HTTP_IF_MODIFIED_SINCE:%]RewriteRule .* — [E=HTTP_IF_NONE_MATCH:%]
The headers are then available in PHP as
$_SERVER [ ‘HTTP_IF_MODIFIED_SINCE’ ];
$_SERVER [ ‘HTTP_IF_NONE_MATCH’ ];
?>
I’ve tested this on PHP/5.1.6, on both Apache/2.2.3/Win32 and Apache/2.0.54/Unix, and it works perfectly.
Note: if you use RewriteRules already for clean URLs, you need to put the above rules AFTER your existing ones.
Superglobal $_SERVER, used in all patches for missing getallheaders() contains only truly basic headers. To pass ANY header into PHP in any httpd environment, including CGI/FCGI just add rule (any number of rules) into .htaccess:
and the header with it’s value will appear for PHP as
And. just couldn’t hold off. Rewrtiting $_SERVER keys for replacing missing function really does not require RegExps, preg_matches or evals. Try this:
function getallheaders () <
foreach( $_SERVER as $K => $V ) < $a = explode ( '_' , $K );
if( array_shift ( $a )== ‘HTTP’ ) <
array_walk ( $a ,function(& $v )< $v = ucfirst ( strtolower ( $v ));>);
$retval [ join ( ‘-‘ , $a )]= $V ;>
> return $retval ; >
?>
The function apache_request_headers, doesn’t exist in FCGI PHP-FPM
// Drop-in replacement for apache_request_headers() when it’s not available
if ( ! function_exists ( ‘apache_request_headers’ ) ) function apache_request_headers () static $arrHttpHeaders ;
if ( ! $arrHttpHeaders )
// Based on: http://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers
$arrCasedHeaders = array(
// HTTP
‘Dasl’ => ‘DASL’ ,
‘Dav’ => ‘DAV’ ,
‘Etag’ => ‘ETag’ ,
‘Mime-Version’ => ‘MIME-Version’ ,
‘Slug’ => ‘SLUG’ ,
‘Te’ => ‘TE’ ,
‘Www-Authenticate’ => ‘WWW-Authenticate’ ,
// MIME
‘Content-Md5’ => ‘Content-MD5’ ,
‘Content-Id’ => ‘Content-ID’ ,
‘Content-Features’ => ‘Content-features’ ,
);
$arrHttpHeaders = array();
foreach ( $_SERVER as $strKey => $mixValue ) if ( ‘HTTP_’ !== substr ( $strKey , 0 , 5 ) ) continue;
>
$strHeaderKey = strtolower ( substr ( $strKey , 5 ) );
if ( 0 < substr_count ( $strHeaderKey , '_' ) ) $arrHeaderKey = explode ( '_' , $strHeaderKey );
$arrHeaderKey = array_map ( ‘ucfirst’ , $arrHeaderKey );
$strHeaderKey = implode ( ‘-‘ , $arrHeaderKey );
> else $strHeaderKey = ucfirst ( $strHeaderKey );
>
if ( array_key_exists ( $strHeaderKey , $arrCasedHeaders ) ) $strHeaderKey = $arrCasedHeaders [ $strHeaderKey ];
>
$arrHttpHeaders [ $strHeaderKey ] = $mixValue ;
>
/** in case you need authorization and your hosting provider has not fixed this for you:
* VHOST-Config:
* FastCgiExternalServer line needs -pass-header Authorization
*
* .htaccess or VHOST-config file needs:
* SetEnvIf Authorization «(.*)» HTTP_AUTHORIZATION=$1
* to add the Authorization header to the environment for further processing
*/
if ( ! empty( $arrHttpHeaders [ ‘Authorization’ ] ) ) // in case of Authorization, but the values not propagated properly, do so 🙂
if ( ! isset( $_SERVER [ ‘PHP_AUTH_USER’ ] ) ) list( $_SERVER [ ‘PHP_AUTH_USER’ ], $_SERVER [ ‘PHP_AUTH_PW’ ] ) = explode ( ‘:’ , base64_decode ( substr ( $_SERVER [ ‘HTTP_AUTHORIZATION’ ], 6 ) ) );
>
>
>
// execute now so other scripts have little chance to taint the information in $_SERVER
// the data is cached, so multiple retrievals of the headers will not cause further impact on performance.
apache_request_headers ();
>
A slightly modified version from limalopex.eisfux.de. Fixes the missing Headers Content-Type and Content-Length and makes it Camel-Case.
if( ! function_exists ( ‘apache_request_headers’ ) ) function apache_request_headers () $arh = array();
$rx_http = ‘/\AHTTP_/’ ;
foreach( $_SERVER as $key => $val ) if( preg_match ( $rx_http , $key ) ) $arh_key = preg_replace ( $rx_http , » , $key );
$rx_matches = array();
// do some nasty string manipulations to restore the original letter case
// this should work in most cases
$rx_matches = explode ( ‘_’ , strtolower ( $arh_key ));
if( count ( $rx_matches ) > 0 and strlen ( $arh_key ) > 2 ) foreach( $rx_matches as $ak_key => $ak_val ) $rx_matches [ $ak_key ] = ucfirst ( $ak_val );
$arh_key = implode ( ‘-‘ , $rx_matches );
>
$arh [ $arh_key ] = $val ;
>
>
if(isset( $_SERVER [ ‘CONTENT_TYPE’ ])) $arh [ ‘Content-Type’ ] = $_SERVER [ ‘CONTENT_TYPE’ ];
if(isset( $_SERVER [ ‘CONTENT_LENGTH’ ])) $arh [ ‘Content-Length’ ] = $_SERVER [ ‘CONTENT_LENGTH’ ];
return( $arh );
>
>
- Apache Functions
- apache_child_terminate
- apache_get_modules
- apache_get_version
- apache_getenv
- apache_lookup_uri
- apache_note
- apache_request_headers
- apache_response_headers
- apache_setenv
- getallheaders
- virtual