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

$_SERVER

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

reserved.variables.server.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека reserved.variables.server.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
$_SERVER

Референца за `reserved.variables.server.php` со подобрена типографија и навигација.

reserved.variables.server.php

$_SERVER

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

$_SERVERИнформации за серверот и околината за извршување

= NULL

$_SERVER е array што содржи информации како што се заглавја, патеки и локации на скрипти. Записите во овој массив се креирани од веб-серверот, затоа нема гаранција дека секој веб-сервер ќе обезбеди некој од овие; серверите може да изостават некои, или да обезбедат други што не се наведени овде. Сепак, повеќето од овие променливи се земени предвид во » CGI/1.1 спецификација, и најверојатно ќе бидат дефинирани.

Забелешка: Кога PHP работи на командна линија повеќето од овие записи нема да бидат достапни или нема да имаат значење.

Покрај елементите наведени подолу, PHP ќе креира дополнителни елементи со вредности од заглавјата на барањето. Овие записи ќе бидат именувани HTTP_ следено од името на заглавјето, со големи букви и со подвлекувања наместо цртички. На пример, Accept-Language заглавјето ќе биде достапно како $_SERVER['HTTP_ACCEPT_LANGUAGE'].

Индекси

'PHP_SELF'
Името на датотеката на тековно извршуваната скрипта, релативно до коренот на документот. На пример, $_SERVER['PHP_SELF'] во скрипта на адреса http://example.com/foo/bar.php ќе биде /foo/bar.phpќе треба да се прилагоди, и __FILE__ константата содржи целосна патека и име на датотеката на тековната (т.е. вклучена) датотека. Ако PHP работи како процесор од командна линија, оваа променлива содржи име на скрипта.
'argv'
Масив од аргументи предадени на скриптата. Кога скриптата се извршува од командна линија, ова дава пристап до параметрите на командната линија сличен на C. Кога се повикува преку GET методот, ова ќе ја содржи низата за прашање.
'argc'
Содржи број на параметри од командната линија предадени на скриптата (ако се извршува од командна линија).
'GATEWAY_INTERFACE'
Каква ревизија на CGI спецификацијата користи серверот; на пр. 'CGI/1.1'.
'SERVER_ADDR'
IP адресата на серверот под кој се извршува тековната скрипта.
'SERVER_NAME'
Името на серверот домаќин под кој се извршува тековната скрипта. Ако скриптата работи на виртуелен домаќин, ова ќе биде вредноста дефинирана за тој виртуелен домаќин.

Забелешка: (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) UseCanonicalName = On and ServerName мора да биде поставено. Инаку, оваа вредност го одразува името на хостот што го дава клиентот, што може да биде лажно. Не е безбедно да се потпрете на оваа вредност во контексти зависни од безбедноста.

'SERVER_SOFTWARE'
Низа за идентификација на серверот, дадена во заглавјата при одговарање на барањата.
'SERVER_PROTOCOL'
Име и ревизија на протоколот за информации преку кој е побарана страницата; на пр. 'HTTP/1.0';
'REQUEST_METHOD'
Кој метод на барање беше искористен за пристап до страницата; на пр. 'GET', 'HEAD', 'POST', 'PUT'.

Забелешка:

PHP скриптата се прекинува по испраќањето на заглавјата (тоа значи по произведување на каков било излез без баферирање на излезот) ако методот на барање беше HEAD.

'REQUEST_TIME'
Временскиот печат кога PHP започна со обработка на барањето.
'REQUEST_TIME_FLOAT'
Временскиот печат кога PHP започна со обработка на барањето, со прецизност до микросекунди.
'QUERY_STRING'
Низата за прашање, ако има, преку која е пристапено до страницата.
'DOCUMENT_ROOT'
Директориумот со коренот на документот под кој се извршува тековната скрипта, како што е дефинирано во конфигурациската датотека на серверот.
'HTTPS'
Поставено на вредност што не е празна ако скриптата била побарана преку HTTPS протоколот.
'REMOTE_ADDR'
IP адресата од која корисникот ја гледа тековната страница.
'REMOTE_HOST'
Името на хостот од кое корисникот ја гледа тековната страница. Обратното пребарување на DNS се базира на REMOTE_ADDR на корисникот.

Забелешка: Веб-серверот мора да биде конфигуриран да ја креира оваа променлива. На пример, во Apache HostnameLookups On мора да биде поставено внатре httpd.conf за да постои. Погледнете исто така gethostbyaddr().

'REMOTE_PORT'
Портата што се користи на машината на корисникот за комуникација со веб-серверот.
'REMOTE_USER'
Автентициран корисник.
'REDIRECT_REMOTE_USER'
Автентициран корисник ако барањето е внатрешно пренасочено.
'SCRIPT_FILENAME'

Апсолутното име на патот на тековно извршуваната скрипта.

Забелешка:

Под Apache 2, file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] Ако скрипта се извршува со CLI, како релативна патека, како на пример

'SERVER_ADMIN'
ќе ја содржи релативната патека специфицирана од корисникот.
'SERVER_PORT'
Вредноста дадена на директивата SERVER_ADMIN (за Apache) во конфигурациската датотека на веб-серверот. Ако скриптата работи на виртуелен хост, ова ќе биде вредноста дефинирана за тој виртуелен хост. '80'Портата на машината на серверот што се користи од веб-серверот за комуникација. За стандардни поставки, ова ќе биде

Забелешка: (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) UseCanonicalName = On; користење SSL, на пример, ќе го промени ова во која било дефинирана сигурна HTTP порта. UseCanonicalPhysicalPort = On , како и

'SERVER_SIGNATURE'
мора да се постави за да се добие физичката (реална) порта, инаку, оваа вредност може да биде лажирана и може, но не мора, да ја врати вредноста на физичката порта. Не е безбедно да се потпирате на оваа вредност во контексти зависни од безбедноста.
'PATH_TRANSLATED'
Низа што ја содржи верзијата на серверот и името на виртуелниот хост што се додаваат на страниците генерирани од серверот, ако се овозможени.

Забелешка: Патека базирана на датотечниот систем (не документ рут) до тековната скрипта, откако серверот направил какво било мапирање од виртуелно во реално. AcceptPathInfo = On inside httpd.conf Корисниците на Apache 2 може да користат PATH_INFO.

'SCRIPT_NAME'
за да дефинираат __FILE__ константата содржи целосна патека и име на датотеката на тековната (т.е. вклучена) датотека.
'REQUEST_URI'
Ја содржи патеката на тековната скрипта. Ова е корисно за страници кои треба да упатуваат на себеси. The/index.html'.
'PHP_AUTH_DIGEST'
URI што беше даден за пристап до оваа страница; на пример, '
'PHP_AUTH_USER'
При вршење Digest HTTP автентикација, оваа променлива се поставува на заглавието 'Authorization' испратено од клиентот (кое потоа треба да го користите за да направите соодветна валидација).
'PHP_AUTH_PW'
При вршење HTTP автентикација, оваа променлива се поставува на корисничкото име обезбедено од корисникот.
'AUTH_TYPE'
При вршење HTTP автентикација, оваа променлива се поставува на лозинката обезбедена од корисникот.
'PATH_INFO'
При вршење HTTP автентикација, оваа променлива се поставува на типот на автентикација. http://www.example.com/php/path_info.php/some/stuff?foo=barСодржи какви било информации за патеката обезбедени од клиентот што следат по името на датотеката на тековната скрипта, но предничат на низата за прашање, ако е достапно. На пример, ако тековната скрипта беше пристапена преку URI $_SERVER['PATH_INFO'] , тогаш /some/stuff.
'ORIG_PATH_INFO'
Оригинална верзија на 'PATH_INFO' пред обработка од PHP.

Примери

Пример #1 $_SERVER example

<?php
echo $_SERVER['SERVER_NAME'];
?>

Горниот пример ќе прикаже нешто слично на:

www.example.com

Белешки

Забелешка:

Ова е 'суперглобална', или автоматска глобална, променлива. Ова едноставно значи дека е достапна во сите опсези низ скрипт. Нема потреба да се global $variable; за пристап до неа во функции или методи.

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

Владимир Корнеа
пред 17 години
1. All elements of the $_SERVER array whose keys begin with 'HTTP_' come from HTTP request headers and are not to be trusted.

2. All HTTP headers sent to the script are made available through the $_SERVER array, with names prefixed by 'HTTP_'.

3. $_SERVER['PHP_SELF'] is dangerous if misused. If login.php/nearly_arbitrary_string is requested, $_SERVER['PHP_SELF'] will contain not just login.php, but the entire login.php/nearly_arbitrary_string. If you've printed $_SERVER['PHP_SELF'] as the value of the action attribute of your form tag without performing HTML encoding, an attacker can perform XSS attacks by offering users a link to your site such as this:

<a href='http://www.example.com/login.php/"><script type="text/javascript">...</script><span a="'>Example.com</a>

The javascript block would define an event handler function and bind it to the form's submit event. This event handler would load via an <img> tag an external file, with the submitted username and password as parameters.

Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. HTML encode every string sent to the browser that should not be interpreted as HTML, unless you are absolutely certain that it cannot contain anything that the browser can interpret as HTML.
vcoletti на tiscali dot it
пред 6 години
To list all the $_SERVER parameters, simply do:

foreach ($_SERVER as $parm => $value)  echo "$parm = '$value'\n";

No need to list all possible keys of the array.
MarkAgius на markagius dot co dot uk
пред 14 години
You have missed 'REDIRECT_STATUS'

Very useful if you point all your error pages to the same file.

File; .htaccess
# .htaccess file.

ErrorDocument 404 /error-msg.php
ErrorDocument 500 /error-msg.php
ErrorDocument 400 /error-msg.php
ErrorDocument 401 /error-msg.php
ErrorDocument 403 /error-msg.php
# End of file.

File; error-msg.php
<?php
  $HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {print "Document has been processed and sent to you.";}
  if($HttpStatus==400) {print "Bad HTTP request ";}
  if($HttpStatus==401) {print "Unauthorized - Iinvalid password";}
  if($HttpStatus==403) {print "Forbidden";}
  if($HttpStatus==500) {print "Internal Server Error";}
  if($HttpStatus==418) {print "I'm a teapot! - This is a real value, defined in 1998";}

?>
Лорд Мек
пред 16 години
An even *more* improved version...

<?php
phpinfo(32);
?>
pierstoval на example dot com
пред 8 години
As PHP $_SERVER var is populated with a lot of vars, I think it's important to say that it's also populated with environment vars.

For example, with a PHP script, we can have this:

    MY_ENV_VAR=Hello php -r 'echo $_SERVER["MY_ENV_VAR"];'
    
Will show "Hello".

But, internally, PHP makes sure that "internal" keys in $_SERVER are not overriden, so you wouldn't be able to do something like this:

    REQUEST_TIME=Hello php -r 'var_dump($_SERVER["REQUEST_TIME"]);'
    
Will show something like 1492897785

However, a lot of vars are still vulnerable from environment injection.

I created a gist here ( https://gist.github.com/Pierstoval/f287d3e61252e791a943dd73874ab5ee ) with my PHP configuration on windows with PHP7.0.15 on WSL with bash, the results are that the only "safe" vars are the following:

PHP_SELF
SCRIPT_NAME
SCRIPT_FILENAME
PATH_TRANSLATED
DOCUMENT_ROOT
REQUEST_TIME_FLOAT
REQUEST_TIME
argv
argc

All the rest can be overriden with environment vars, which is not very cool actually because it can break PHP applications sometimes...

(and I only tested on CLI, I had no patience to test with Apache mod_php or Nginx + PHP-FPM, but I can imagine that not a lot of $_SERVER properties are "that" secure...)
jonbarnett на gmail dot com
пред 17 години
It's worth noting that $_SERVER variables get created for any HTTP request headers, including those you might invent:

If the browser sends an HTTP request header of:
X-Debug-Custom: some string

Then:

<?php
$_SERVER['HTTP_X_DEBUG_CUSTOM']; // "some string"
?>

There are better ways to identify the HTTP request headers sent by the browser, but this is convenient if you know what to expect from, for example, an AJAX script with custom headers.

Works in PHP5 on Apache with mod_php.  Don't know if this is true from other environments.
Ричард Јорк
пред 16 години
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.

 ["_SERVER"]=>
  array(24) {
    ["MANPATH"]=>
    string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man"
    ["TERM"]=>
    string(11) "xterm-color"
    ["SHELL"]=>
    string(9) "/bin/bash"
    ["SSH_CLIENT"]=>
    string(20) "127.0.0.1 41242 22"
    ["OLDPWD"]=>
    string(60) "/Library/WebServer/Domains/www.example.com/private"
    ["SSH_TTY"]=>
    string(12) "/dev/ttys000"
    ["USER"]=>
    string(5) "username"
    ["MAIL"]=>
    string(15) "/var/mail/username"
    ["PATH"]=>
    string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"
    ["PWD"]=>
    string(56) "/Library/WebServer/Domains/www.example.com/www"
    ["SHLVL"]=>
    string(1) "1"
    ["HOME"]=>
    string(12) "/Users/username"
    ["LOGNAME"]=>
    string(5) "username"
    ["SSH_CONNECTION"]=>
    string(31) "127.0.0.1 41242 10.0.0.1 22"
    ["_"]=>
    string(12) "/usr/bin/php"
    ["__CF_USER_TEXT_ENCODING"]=>
    string(9) "0x1F5:0:0"
    ["PHP_SELF"]=>
    string(10) "Shell.php"
    ["SCRIPT_NAME"]=>
    string(10) "Shell.php"
    ["SCRIPT_FILENAME"]=>
    string(10) "Shell.php"
    ["PATH_TRANSLATED"]=>
    string(10) "Shell.php"
    ["DOCUMENT_ROOT"]=>
    string(0) ""
    ["REQUEST_TIME"]=>
    int(1247162183)
    ["argv"]=>
    array(1) {
      [0]=>
      string(10) "Shell.php"
    }
    ["argc"]=>
    int(1)
  }
chris на ocproducts dot com
пред 8 години
Guide to URL paths...

Data: $_SERVER['PHP_SELF']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info (see $_SERVER['PATH_INFO']) and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)

Data: $_SERVER['SCRIPT_NAME']
Data type: String
Purpose: The URL path name of the current PHP file, excluding path-info and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Caveat: Not set on all PHP environments, may need setting via preg_replace('#\.php/.*#', '.php', $_SERVER['PHP_SELF']).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)

Data: $_SERVER['REDIRECT_URL']
Data type: String
Purpose: The URL path name of the current PHP file, path-info is N/A and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL).
Caveat: Not set on all PHP environments, and definitely only ones with URL rewrites.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['REQUEST_URI']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info and including URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL). *
*: I've seen at least one situation where this is not true (there was another $_SERVER variable to use instead supplied by the URL rewriter), but the author of the URL rewriter later fixed it so probably fair to dismiss this particular note.
Caveat: Not set on all PHP environments, may need setting via $_SERVER['REDIRECT_URL'] . '?' . http_build_query($_GET) [if $_SERVER['REDIRECT_URL'] is set, and imperfect as we don't know what GET parameters were originally passed vs which were injected in the URL rewrite] --otherwise-- $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['PATH_INFO']
Data type: String
Purpose: Find the path-info, which is data after the .php filename in the URL call. It's a strange concept.
Caveat: Some environments may not support it, it is best avoided unless you have complete server control
Works on web mode: Yes
Works on CLI mode: No

Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.
krinklemail на gmail dot com
пред 13 години
If requests to your PHP script send a header "Content-Type" or/ "Content-Length" it will, contrary to regular HTTP headers, not appear in $_SERVER as $_SERVER['HTTP_CONTENT_TYPE']. PHP removes these (per CGI/1.1 specification[1]) from the HTTP_ match group.

They are still accessible, but only if the request was a POST request. When it is, it'll be available as:
$_SERVER['CONTENT_LENGTH']
$_SERVER['CONTENT_TYPE']

[1] https://www.ietf.org/rfc/rfc3875
chris на ocproducts dot com
пред 8 години
Guide to absolute paths...

Data: __FILE__
Data type: String
Purpose: The absolute pathname of the running PHP file, including the filename.
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes

Data: __DIR__
Data type: String
Purpose: The absolute pathname to the running PHP file, excluding the filename
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes

Data: $_SERVER['SCRIPT_FILENAME']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: Not set on all PHP environments, may need setting by copying from __FILE__ before other files are included.
Caveat: Symbolic links are not pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Caveat: "Filename" makes you think it is just a filename, but it really is the full absolute pathname. Read the identifier as "Script's filesystem (path)name".
Works on web mode: Yes
Works on CLI mode: Yes

Data: $_SERVER['PATH_TRANSLATED']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: It's probably not set, best to just not use it. Just use realpath($_SERVER['SCRIPT_FILENAME']) (and be aware that itself may need to have been emulated).
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['DOCUMENT_ROOT']
Data type: String
Purpose: Get the absolute path to the web server's document root. No trailing slash.
Caveat: Don't trust this to be set, or set correctly, unless you control the server environment.
Caveat: May or may not have symbolic links pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: No

Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.

Note that if you call "php --info" on the command line then naturally some of these settings are going to be blank, as no PHP file is involved.
Ако скрипта се извршува со CLI, како релативна патека, како на пример
пред 4 години
If you need to know the protocol (http or https) used by the client, then the $_SERVER['HTTPS'] variable may not actually report the truth if your server is behind a proxy or a load balancer (In fact the client could connect to the load balancer using https, and then the load balancer forward the request to the server using http).
If the proxy/load balancer is correctly configured it could send the original request protocol in a header, and you will find it in the $_SERVER[HTTP_X_FORWARDED_PROTO] variable.
ywarnier на beeznest dot org
пред 8 години
Note that $_SERVER['REQUEST_URI'] might include the scheme and domain in certain cases.

This happens, for example, when calling the page through a call to stream_context_create() with a HTTP header of 'request_fulluri' set to 1.

For example:

$http = ['request_fulluri' => 1, /* other params here */];
$context = stream_context_create(array( 'http' => $http ));
$fp = fopen($some_url, 'rb', false, $context);

When outputting $_SERVER['REQUEST_URI'] on the server at $some_url, you will get
https://some_url/some_script.php

Remove the request_fulluri => 1 option, and $_SERVER['REQUEST_URI'] gets back to its "normal":
/some_script.php

Apparently, request_fulluri is useful when using some proxy servers.

In this case, there is no proper way to "detect" if this option was set or not, and you should probably use a combination of other $_SERVER[] elements (like REQUEST_SCHEME, SERVER_NAME and SERVER_PORT) to determine if this was the case.

One quick (and improvable) way to detect it would be to compare the start of the REQUEST_URI with REQUEST_SCHEME:

$scheme = $_SERVER['REQUEST_SCHEME'] . '://';
if (strcmp(substr($_SERVER['REQUEST_URI'], 0, strlen($scheme)), $scheme) === 0) {
    // request_fulluri was set
}
lemonostif на gmail dot com
пред 6 години
PHP_SELF is a disgrace of a programmer's work. One of the most widespread PHP vulnerabilities since version 4 and the manual says nothing about the dangers. At least clarify that ITS VALUE CAN BE PROVIDED BY THE USER with capitals preferably if you want to make the internet a safer place...
Стефано (info на sarchittu dot org)
пред 15 години
A way to get the absolute path of your page, independent from the site position (so works both on local machine and on server without setting anything) and from the server OS (works both on Unix systems and Windows systems).

The only parameter it requires is the folder in which you place this script
So, for istance, I'll place this into my SCRIPT folder, and I'll write SCRIPT word length in $conflen

<?php
$conflen=strlen('SCRIPT');
$B=substr(__FILE__,0,strrpos(__FILE__,'/'));
$A=substr($_SERVER['DOCUMENT_ROOT'], strrpos($_SERVER['DOCUMENT_ROOT'], $_SERVER['PHP_SELF']));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$D;
?>

$host will finally contain the absolute path.
Марк Симон
пред 6 години
So near, and yet so far …

$_SERVER has nearly everything you need to know about the current web page environment. Something which would have been handy is easy access to the protocol and the actual web root.

For the protocol, you may or may not have $_SERVER['HTTPS'] and it may or may not be empty. For the web root, $_SERVER['DOCUMENT_ROOT'] depends on the server configuration, and doesn’t work for virtual hosts.

For practical purposes, I normally include something like the following in my scripts:

<?php
    //    Web Root
    //    Usage: include("$root/includes/something.inc.php");
        $root = $_SERVER['WEB_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'],'',$_SERVER['SCRIPT_FILENAME']);

    //    Host & Protocol
    //    Usage: $url = "$protocol://$host/images/something.jpg";
        $host = $_SERVER['HTTP_HOST'];
        $protocol=$_SERVER['PROTOCOL'] = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http';
?>
steve на sc-fa dot com
пред 16 години
If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.   

$_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR']

$_SERVER['HTTP_X_FORWARDED_HOST'] and 
$_SERVER['HTTP_X_FORWARDED_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME']
info на mtprod dot com
пред 17 години
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
Тонин
пред 17 години
When using the $_SERVER['SERVER_NAME'] variable in an apache virtual host setup with a ServerAlias directive, be sure to check the UseCanonicalName apache directive.  If it is On, this variable will always have the apache ServerName value.  If it is Off, it will have the value given by the headers sent by the browser.

Depending on what you want to do the content of this variable, put in On or Off.
jarrod на squarecrow dot com
пред 16 години
$_SERVER['DOCUMENT_ROOT'] is incredibly useful especially when working in your development environment. If you're working on large projects you'll likely be including a large number of files into your pages. For example:

<?php
//Defines constants to use for "include" URLS - helps keep our paths clean

        define("REGISTRY_CLASSES",  $_SERVER['DOCUMENT_ROOT']."/SOAP/classes/");
        define("REGISTRY_CONTROLS", $_SERVER['DOCUMENT_ROOT']."/SOAP/controls/");

        define("STRING_BUILDER",     REGISTRY_CLASSES. "stringbuilder.php");
        define("SESSION_MANAGER",     REGISTRY_CLASSES. "sessionmanager.php");
        define("STANDARD_CONTROLS",    REGISTRY_CONTROLS."standardcontrols.php");
?>

In development environments, you're rarely working with your root folder, especially if you're running PHP locally on your box and using DOCUMENT_ROOT is a great way to maintain URL conformity. This will save you hours of work preparing your application for deployment from your box to a production server (not to mention save you the headache of include path failures).
7 белешки
пред 13 години
Be warned that most contents of the Server-Array (even $_SERVER['SERVER_NAME']) are provided by the client and can be manipulated. They can also be used for injections and thus MUST be checked and treated like any other user input.
pomat на live dot it
12 години пред
$_SERVER['DOCUMENT_ROOT'] may contain backslashes on windows systems, and of course it may or may not have a trailing slash (backslash).
I saw the following as an example of the proper way we're supposed to deal with this issue:

<?php
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php');
?>

Ok, the latter may be used to access a file inside the parent directory of the document root, but actually does not properly address the issue.
In the end, don't warry about. It should be safe to use forward slashes and append a trailing slash in all cases.
Let's say we have this:

<?php
$path = 'subdir/file.php';
$result = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
?>

On linux $result might be something like
1) "/var/www/subdir/file.php"
2) "/var/www//subdir/file.php"
String 2 is parsed the same as string 1 (have a try with command 'cd').

On windows $result might be something like
1) "C:/apache/htdocs/subdir/file.php"
2) "C:/apache/htdocs//subdir/file.php"
3) "C:\apache\htdocs/subdir/file.php"
4) "C:\apache\htdocs\/subdir/file.php"
All those strings are parsed as "C:\apache\htdocs\subdir\file.php" (have a try with 'cd').
chris
пред 16 години
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
pudding06 на gmail dot com
пред 16 години
Here's a simple, quick but effective way to block unwanted external visitors to your local server:

<?php
// only local requests
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') die(header("Location: /"));
?>

This will direct all external traffic to your home page. Of course you could send a 404 or other custom error. Best practice is not to stay on the page with a custom error message as you acknowledge that the page does exist. That's why I redirect unwanted calls to (for example) phpmyadmin.
picov на e-link dot it
пред 14 години
A simple function to detect if the current page address was rewritten by mod_rewrite:

<?php
public function urlWasRewritten() {
  $realScriptName=$_SERVER['SCRIPT_NAME'];
  $virtualScriptName=reset(explode("?", $_SERVER['REQUEST_URI']));
  return !($realScriptName==$virtualScriptName);
}
?>
lilJoshu
пред 7 години
Remember,

Although $_SERVER["REQUEST_METHOD"] is initially built with GET, POST, PUT, HEAD in mind, a server can allow more. 

This may be important if you're building a RESTful interfaces that will also use methods such as PATCH and DELETE.

Also important as a security risk as a possible point of injection. In the event of building something acting based on REQUEST_METHOD, it's recommended to put it in a switch statement.

<?php
switch ($_SERVER["REQUEST_METHOD"]){
   case "PUT":
       foo_replace_data();
       break;
   case "POST":
       foo_add_data();
       break;
   case "HEAD";
       foo_set_that_cookie();
       break;
   case "GET":
   default:
      foo_fetch_stuff()
      break;
}

?>
kamil00110
пред 2 години
This code can be used to help find somone that tries to dig throught the server files to find something.

.htaccess

ErrorDocument 404 /your.php
ErrorDocument 403 /your.php

<?php  
         //get time
         $time = date("H:i:s d.m.y"); 
         //get user address
         $usr = $_SERVER['REMOTE_ADDR'];    
         //get entered url of the "visitor"
         $url = $_SERVER['REQUEST_URI'];
         //get your servers address
         $ip = $_SERVER['SERVER_ADDR'];
     //put toogether
         $sus = "[".$time."]   ".$usr."   ".$ip.$url.PHP_EOL;    
         //write an log file     
         file_put_contents("susip.txt", $sus, FILE_APPEND);
?>
php на isnoop dot net
пред 15 години
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"
mirko dot steiner на slashdevslashnull dot de
пред 16 години
<?php

// RFC 2616 compatible Accept Language Parser
// http://www.ietf.org/rfc/rfc2616.txt, 14.4 Accept-Language, Page 104
// Hypertext Transfer Protocol -- HTTP/1.1

foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
    $pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})'.
    '(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)'.
    '(?P<quantifier>\d\.\d))?$/';

    $splits = array();

    printf("Lang:,,%s''\n", $lang);
    if (preg_match($pattern, $lang, $splits)) {
        print_r($splits);
    } else {
        echo "\nno match\n";
    }
}

?>

example output:

Google Chrome 3.0.195.27 Windows xp

Lang:,,de-DE''
Array
(
    [0] => de-DE
    [primarytag] => de
    [1] => de
    [subtag] => DE
    [2] => DE
)
Lang:,,de;q=0.8''
Array
(
    [0] => de;q=0.8
    [primarytag] => de
    [1] => de
    [subtag] => 
    [2] => 
    [quantifier] => 0.8
    [3] => 0.8
)
Lang:,,en-US;q=0.6''
Array
(
    [0] => en-US;q=0.6
    [primarytag] => en
    [1] => en
    [subtag] => US
    [2] => US
    [quantifier] => 0.6
    [3] => 0.6
)
Lang:,,en;q=0.4''
Array
(
    [0] => en;q=0.4
    [primarytag] => en
    [1] => en
    [subtag] => 
    [2] => 
    [quantifier] => 0.4
    [3] => 0.4
)
wbeaumo1 на gmail dot com
пред 15 години
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
silverquick на gmail dot com
пред 17 години
I think the HTTPS element will only be present under Apache 2.x. It's not in the list of "special" variables here:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond
But it is here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond
chris на ocproducts dot com
пред 8 години
Guide to script parameters...

Data: $_GET
Data type: Array (map)
Purpose: Contains all GET parameters (i.e. a parsed URL query string).
Caveat: GET parameter names have to be compliant with PHP variable naming, e.g. dots are not allowed and get substituted.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['QUERY_STRING']
Data type: String
Purpose: Gets an unparsed URL query string.
Caveat: Not set on all PHP environments, may need setting via http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['argv']
Data type: Array (list)
Purpose: Get CLI call parameters.
Works on web mode: Tenuous (just contains a single parameter, the query string)
Works on CLI mode: Yes
На оваа страница

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

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

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

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

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