PHP.mk документација

apache_request_headers

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.apache-request-headers.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.apache-request-headers.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
apache_request_headers

Референца за `function.apache-request-headers.php` со подобрена типографија и навигација.

function.apache-request-headers.php

apache_request_headers

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

apache_request_headersПреземи ги сите HTTP заглавија на барањето

= NULL

apache_request_headers(): array

Презема сите HTTP заглавија на барањето од тековното барање. Работи на веб-серверите Apache, FastCGI, CLI и FPM.

Параметри

Оваа функција нема параметри.

Вратени вредности

Асоцијативен низ од сите HTTP заглавија во тековното барање.

Дневник на промени

Верзија = NULL
7.3.0 Оваа функција стана достапна во FPM SAPI.

Примери

Пример #1 apache_request_headers() example

<?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

Белешки

Забелешка:

Можете исто така да ја добиете вредноста на вообичаените CGI променливи со читање од околината, што работи без разлика дали користите PHP како Апачи модул. Користете phpinfo() за да видите список на сите достапни променливи на околината.

Види Исто така

Белешки од корисници 5 белешки

Тел
пред 6 години
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.
callum85 на notspam точка msn точка com
пред 18 години
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:%{HTTP:If-Modified-Since}]
RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]

The headers are then available in PHP as
<?php
  $_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.
limalopex.eisfux.de
19 години пред
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:

<?php
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 );
}
///
}
///
?>
egocentryk
пред 11 години
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:

RewriteRule .* - [E=HTTP_MY_HEADER:%{HTTP:My-Header}]

and the header with it's value will appear for PHP as 
<?php print $_SERVER['HTTP_MY_HEADER']; ?>

And... just couldn't hold off. Rewrtiting $_SERVER keys for replacing missing function really does not require RegExps, preg_matches or evals... Try this:
<?php
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; }
 ?>
gilles на sdv точка fr
3 години пред
The function apache_request_headers, doesn't exist in FCGI PHP-FPM

Use this patch : https://gist.github.com/rmpel/11583cfddfcc9705578428e3a2ee3dc1

<?php
// 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 ) ) );
                }
            }
        }

        return $arrHttpHeaders;
    }

    // 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();
}
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.