It looks a lot simpler to me than most of the examples given in other answers. This also gets the method (GET/POST/etc.) and the URI requested when getting all of the headers which can be useful if you're trying to use it in logging.
To make things simple, here is how you can get just the one you want:
Simple:
$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH'];
or when you need to get one at a time:
<?php
/**
* @param $pHeaderKey
* @return mixed
*/
function get_header( $pHeaderKey )
{
// Expanded for clarity.
$headerKey = str_replace('-', '_', $pHeaderKey);
$headerKey = strtoupper($headerKey);
$headerValue = NULL;
// Uncomment the if when you do not want to throw an undefined index error.
// I leave it out because I like my app to tell me when it can't find something I expect.
//if ( array_key_exists($headerKey, $_SERVER) ) {
$headerValue = $_SERVER[ $headerKey ];
//}
return $headerValue;
}
// X-Requested-With mainly used to identify Ajax requests. Most JavaScript frameworks
// send this header with value of XMLHttpRequest, so this will not always be present.
$header_x_requested_with = get_header( 'X-Requested-With' );
I was using CodeIgniter and used the code below to get it. May be useful for someone in future.
This small PHP snippet can be helpful to you:
Since PHP 5.4.0 you can use
getallheaders
function which returns all requested headers as an associative array:Earlier this function worked only when PHP was running as an Apache/NSAPI module.
Here's how I'm doing it. You need to get all headers if $header_name isn't passed:
It looks a lot simpler to me than most of the examples given in other answers. This also gets the method (GET/POST/etc.) and the URI requested when getting all of the headers which can be useful if you're trying to use it in logging.
Here's the output:
Here is an easy way to do it.
To make things simple, here is how you can get just the one you want:
Simple:
or when you need to get one at a time:
The other headers are also in the super global array $_SERVER, you can read about how to get at them here: http://php.net/manual/en/reserved.variables.server.php