PHP에서 요청 헤더를 읽는 방법
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'];
그렇지 않은 경우: PHP를 Apache 모듈로 실행하거나 PHP 5.4에서 FastCGI(간단한 방법)를 사용합니다.
<?php
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
기타: 다른 경우 (사용자랜드 구현)를 사용할 수 있습니다.
<?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']
RFC 3875, 4.1.18:
이름이 다음 문자로 시작하는 메타 변수
HTTP_
사용되는 프로토콜이 HTTP인 경우 클라이언트 요청 헤더 필드에서 읽은 값을 포함합니다.HTTP 헤더필드명이 대문자로 변환되어 모든 항목이-
로 대체하다_
및 가지고 있다HTTP_
메타데이터 이름을 붙이려고 합니다.
에서 모든 HTTP 헤더를 찾을 수 있습니다.$_SERVER
프레픽스가 붙은 글로벌 변수HTTP_
대문자 기호(-)를 밑줄(_)로 바꿉니다.
예를 들면,X-Requested-With
다음 사이트에서 찾을 수 있습니다.
$_SERVER['HTTP_X_REQUESTED_WITH']
에서 관련지어 어레이를 작성하는 것이 편리할 수 있습니다.$_SERVER
변수.이것은 몇 가지 스타일로 할 수 있지만, 여기에 camelcase 키를 출력하는 기능이 있습니다.
$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에서는 모든 요청 헤더를 연관 배열로 반환하는 함수를 사용할 수 있습니다.
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 모듈로 실행 중일 때만 이 함수가 작동했습니다.
CodeIgniter를 사용하고 있었는데, 아래의 코드를 사용하여 취득했습니다.미래에 누군가에게 유용할 수 있습니다.
$this->input->get_request_header('X-Requested-With');
strtolower
는 제안된 솔루션 중 몇 가지에 결여되어 있습니다.RFC 2616(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
loop. 헤더를 찾을 수 없으면 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 를 참조하십시오.
이 이 함수는: 이는 a a a a a a a a a a a a a a a a a보다 성능이 떨어집니다.또한 이 함수는 이 함수에 비해 퍼포먼스가 떨어집니다.for
loopsyslog.syslog..syslog.
필요한 예: 키만 있으면 됩니다)."Host"
.★★★★★★★★★★★★★★★★★★,
apache_request_headers()['Host']
루프를 회피하고 에코 출력에 인라인으로 접속할 수 있도록 합니다.
간단히 말하면, 원하는 것을 얻을 수 있는 방법은 다음과 같습니다.
심플:
$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 를 참조해 주세요.
이게 내가 하는 방법이야.$header_name이 전달되지 않으면 모든 헤더를 가져와야 합니다.
<?php
function getHeaders($header_name=null)
{
$keys=array_keys($_SERVER);
if(is_null($header_name)) {
$headers=preg_grep("/^HTTP_(.*)/si", $keys);
} else {
$header_name_safe=str_replace("-", "_", strtoupper(preg_quote($header_name)));
$headers=preg_grep("/^HTTP_${header_name_safe}$/si", $keys);
}
foreach($headers as $header) {
if(is_null($header_name)){
$headervals[substr($header, 5)]=$_SERVER[$header];
} else {
return $_SERVER[$header];
}
}
return $headervals;
}
print_r(getHeaders());
echo "\n\n".getHeaders("Accept-Language");
?>
다른 답변에 제시된 대부분의 예보다 훨씬 단순해 보입니다.또, 모든 헤더를 취득할 때에 요구된 메서드(GET/POST/etc)와 URI도 취득합니다.이러한 URI는 로깅에 사용할 때 편리합니다.
출력은 다음과 같습니다.
Array ( [HOST] => 127.0.0.1 [USER_AGENT] => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0 [ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [ACCEPT_LANGUAGE] => en-US,en;q=0.5 [ACCEPT_ENCODING] => gzip, deflate [COOKIE] => PHPSESSID=MySessionCookieHere [CONNECTION] => keep-alive )
en-US,en;q=0.5
PHP 7: Null 병합 연산자
//$http = 'SCRIPT_NAME';
$http = 'X_REQUESTED_WITH';
$http = strtoupper($http);
$header = $_SERVER['HTTP_'.$http] ?? $_SERVER[$http] ?? NULL;
if(is_null($header)){
die($http. ' Not Found');
}
echo $header;
여기 그것을 하는 쉬운 방법이 있다.
// echo get_header('X-Requested-With');
function get_header($field) {
$headers = headers_list();
foreach ($headers as $header) {
list($key, $value) = preg_split('/:\s*/', $header);
if ($key == $field)
return $value;
}
}
이 작은 PHP 스니펫은 도움이 될 수 있습니다.
<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>
function getCustomHeaders()
{
$headers = array();
foreach($_SERVER as $key => $value)
{
if(preg_match("/^HTTP_X_/", $key))
$headers[$key] = $value;
}
return $headers;
}
이 함수를 사용하여 커스텀헤더를 가져옵니다.헤더가 "HTTP_X_"에서 시작하면 어레이를 푸시합니다. : )
Apache 서버가 있는 경우 이 작업을 수행합니다.
PHP 코드:
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
결과:
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive
아래 코드는 헤더에 특정 데이터를 제출하는 데 도움이 됩니다.
foreach (getallheaders() as $name => $value) {
if($name=='Authorization') //here you can search by name
$Authorization= $value ;
}
언급URL : https://stackoverflow.com/questions/541430/how-do-i-read-any-request-header-in-php
'sourcecode' 카테고리의 다른 글
날짜 및 시각에서 DATETIME 생성 (0) | 2023.01.15 |
---|---|
SQL 연금술 로드 테스트: "Timeout Error:크기 3 오버플로우 0의 QueuePool 제한에 도달했으며 연결 시간 초과, 시간 초과 30" (0) | 2023.01.15 |
교육 후 모델을 저장/복원하는 방법 (0) | 2023.01.10 |
subprocess.call()의 출력을 취득하고 있습니다. (0) | 2023.01.10 |
Python의 'in' 연산자를 재정의하시겠습니까? (0) | 2023.01.10 |