PHP에서 헤더를 어떻게 읽습니까?
예를 들어 맞춤 헤더 : X-Requested-With.
답변
IF : 모든 헤더 대신 단일 헤더 만 필요한 경우 가장 빠른 방법은 다음과 같습니다.
<?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 : PHP를 Apache 모듈로 또는 PHP 5.4에서 FastCGI (간단한 방법)를 사용하여 실행합니다.
<?php
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}ELSE : 다른 경우에는 (사용자 구현)을 사용할 수 있습니다.
<?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";
}
참조 : 
getallheaders () -(PHP> = 5.4) 플랫폼 간 에디션 apache_request_headers()
apache_response_headers ()의 별칭 -모든 HTTP 응답 헤더를 가져 옵니다 . 
headers_list () -전송할 헤더 목록을 가져 옵니다 .
답변
$_SERVER['HTTP_X_REQUESTED_WITH']RFC3875 , 4.1.18 :
HTTP_사용 된 프로토콜이 HTTP 인 경우 이름이 시작하는 메타 변수 에는 클라이언트 요청 헤더 필드에서 읽은 값 이 포함됩니다. 는 HTTP 헤더 필드 이름은 대문자로 변환되고, 모든 항목이-대체를_하고있다HTTP_메타 변수 이름을 앞에 추가.
답변
$_SERVER접두사가 붙은 전역 변수 에서 모든 HTTP 헤더를 찾아야합니다.HTTP_대문자로 하고 대시 (-)를 밑줄 (_)로 대체 한 .
예를 들어 다음 X-Requested-With에서 찾을 수 있습니다.
$_SERVER['HTTP_X_REQUESTED_WITH']$_SERVER변수 에서 연관 배열을 작성하는 것이 편리 할 수 있습니다 . 여러 스타일로 수행 할 수 있지만 다음은 camelcased 키를 출력하는 기능입니다.
$headers = array();
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
    }
}이제 $headers['XRequestedWith']원하는 헤더를 검색하는 데 사용 하십시오.
PHP 매뉴얼 $_SERVER: http://php.net/manual/en/reserved.variables.server.php
답변
PHP 5.4.0부터 getallheaders모든 요청 헤더를 연관 배열로 반환 하는 함수를 사용할 수 있습니다 .
var_dump(getallheaders());
// array(8) {
//   ["Accept"]=>
//   string(63) "text/html[...]"
//   ["Accept-Charset"]=>
//   string(31) "ISSO-8859-1[...]"
//   ["Accept-Encoding"]=>
//   string(17) "gzip,deflate,sdch"
//   ["Accept-Language"]=>
//   string(14) "en-US,en;q=0.8"
//   ["Cache-Control"]=>
//   string(9) "max-age=0"
//   ["Connection"]=>
//   string(10) "keep-alive"
//   ["Host"]=>
//   string(9) "localhost"
//   ["User-Agent"]=>
//   string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [...]"
// }이전에는이 기능이 PHP가 Apache / NSAPI 모듈로 실행될 때만 작동했습니다.
답변
strtolowerRFC2616 (HTTP / 1.1)은 헤더 필드를 대소 문자를 구분하지 않는 엔티티로 정의합니다. 가치 뿐만 아니라 모든 것 부분 .
따라서 HTTP_ 구문 분석과 같은 제안 항목 은 잘못되었습니다.
더 나은 방법은 다음과 같습니다.
if (!function_exists('getallheaders')) {
    foreach ($_SERVER as $name => $value) {
        /* RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. */
        if (strtolower(substr($name, 0, 5)) == 'http_') {
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
        }
    }
    $this->request_headers = $headers;
} else {
    $this->request_headers = getallheaders();
}이전 제안과 미묘한 차이점이 있습니다. 이 함수는 php-fpm (+ nginx)에서도 작동합니다.
답변
for루프 를 사용하지 않고 값을 얻으려면 헤더 이름을이 함수에 전달하십시오 . 헤더를 찾지 못하면 null을 반환합니다.
/**
 * @var string $headerName case insensitive header name
 *
 * @return string|null header value or null if not found
 */
function get_header($headerName)
{
    $headers = getallheaders();
    return isset($headerName) ? $headers[$headerName] : null;
}참고 : 이것은 Apache 서버에서만 작동합니다 .http : //php.net/manual/en/function.getallheaders.php 참조
참고 :이 함수는 모든 헤더를 처리하고 메모리에로드하며 for루프 보다 성능이 떨어집니다 .
답변
일을 간단하게하기 위해 원하는 것을 얻을 수있는 방법은 다음과 같습니다.
단순한:
$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH'];또는 한 번에 하나씩 받아야하는 경우 :
<?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' );다른 헤더는 슈퍼 글로벌 배열 $ _SERVER에도 있습니다. http://php.net/manual/en/reserved.variables.server.php
