When using a php script like a remote function call, I find something like this useful for setting default parameters.
<?php
/**
/* combine _GET _POST _COOKIE variables with provided default values
/* defaults - associative array of default values
/* overwrite - if true, write result to _REQUEST superglobal
/* super_globals - array of super globals to fetch values from
**/
function get_params($defaults = null, $overwrite = false, $super_globals = array('_GET', '_POST', '_COOKIE'))
{
$ret = array();
// fetch values from request
foreach($super_globals as $sg)
foreach($GLOBALS[$sg] as $k=>$v)
$ret[$k] = $v;
// apply defaults for missing parameters
if($defaults) foreach($defaults as $k=>$v)
if(!isset($ret[$k]))
$ret[$k] = $v;
if($overwrite)
$_REQUEST = $ret;
return $ret;
}
// Example: page.php?style=modern
$argv = get_params(array('id'=>42, 'style'=>'medieval'));
// $argv['id'] = 42
// $argv['style'] = 'modern'
?>
기선언 변수
PHP 4.1.0이후부터 외부 변수를 가져오는 가장 선호되는 방법은 아래에서 설명하는 슈퍼전역을 사용하는것이다. 그 이전버전에서는 register_globals이나 긴형태의 기선언 PHP 배열($HTTP_*_VARS)을 사용한다. PHP 5.0.0부터, 긴 형태의 PHP 예약 변수 배열을 register_long_arrays 지시어로 제거할 수 있습니다.
서버 변수: $_SERVER
Note: 4.1.0부터 지원됨. 이전 버전은 $HTTP_SERVER_VARS을 사용함
$_SERVER는 헤더, 경로, 스크립트 위치와 같은 정보를 포함하는 배열이다. 이 배열 안의 엔트리는 웹서버에 의해 생성된다. 모든 웹서버가 이런 것들을 제공한다는 보장은 없다. 서버는 어떤것은 빠뜨리거나 여기에서 목록화된 것 외의 것을 제공할수 도 있다. 이런 많은 수의 변수들은 » CGI 1.1 specification에 기반하므로, 그런 변수들은 기대할수 있을것이다.
이 변수는 '슈퍼전역', 또는 자동 전역, 변수이다. 즉 스크립트내의 모든 유효영역안에서 사용가능하다는 의미를 갖는다. $HTTP_SERVER_VARS를 사용할때와 같이 함수나 메소드 안에서 사용하기 위해 global $_SERVER;를 할 필요는 없다.
$HTTP_SERVER_VARS는 동일한 초기 정보를 포함하지만, 자동전역은 아니다. ($HTTP_SERVER_VARS 와 $_SERVER는 다른 변수이고 PHP는 그변수들을 따로 다루게 된다는 것에 주의한다)
register_globals 디렉티브가 설정되어있으면, 이 변수들은 스크립트의 전역 유효영역에서 사용이 가능해 진다. 즉 $_SERVER 와 $HTTP_SERVER_VARS 배열과 분리된다. 관련정보는 전역 등록 사용하기라는 이름의 보안 챕터를 참고한다. 이들 각각의 전역은 자동전역이 아니다.
$_SERVER에서는 다음 구성요소를 확인할수도 있고 그렇지 않은수있다. 이 변수중 일부(심지어 모두)는 PHP가 커맨드 라인에서 수행되고 있을때에는 보여지지 않을것이다.
- 'PHP_SELF'
- 현재 실행중인 스크립트의 파일명이고, 도규먼트 루트에 상대적인 경로를 갖는다. 예를 들면, 주소 http://example.com/test.php/foo.bar의 스크립트에서 $_SERVER['PHP_SELF']은 /test.php/foo.bar이 될것이다. PHP가 커맨드 라인 프로세서로 실행중이면, 이 변수는 나타나지 않는다.
- 'argv'
- 스크립트로 전달되는 인자의 배열. 스크립트가 커맨드 라인에서 실행중이면, 이 변수는 C-스타일의 커맨드 라인 인자로 제공된다. GET 메소드에 의해 호출될때에는 이 변수는 질의 문자열(query string)을 포함할것이다.
- 'argc'
- 스크립트로 전달되는 커맨드 라인 인자의 갯수 (커맨드 라인에서 실행중일때)
- 'GATEWAY_INTERFACE'
- 서버가 사용하는 CGI 사양(specification)의 버전: 예를 들면, 'CGI/1.1'.
- 'SERVER_NAME'
- 현재 스크립트가 수행되고 있는 서버 호스트의 이름. 스크립트가 가상 호스트에서 수행중이면, 이 변수는 그 가상 호스트를 위해 정의된 값이 될것이다.
- 'SERVER_SOFTWARE'
- 서버 식별 문자열. 요구(ruquest)에 응답할때 헤더안에서 보여준다.
- 'SERVER_PROTOCOL'
- 페이지가 요청되어진 정보 프로토콜의 이름과 버전: 예를 들면, 'HTTP/1.0';
- 'REQUEST_METHOD'
- 페이지에 접근할때 사용된 요청 메소드 종류. 예를 들면,'GET', 'HEAD', 'POST', 'PUT'.
- 'QUERY_STRING'
- 페이지가 접근될때의 질의 문자열
- 'DOCUMENT_ROOT'
- 현재 스크립트가 수행중인 다큐먼트 루트 디렉토리. 서버 설정 파일에서 정의된다.
- 'HTTP_ACCEPT'
- 현재 요청에 대한 Accept: 헤더의 내용.
- 'HTTP_ACCEPT_CHARSET'
- 현재 요청에 대한 Accept-Charset: 헤더의 내용. 예를 들면'iso-8859-1,*,utf-8'.
- 'HTTP_ACCEPT_ENCODING'
- 현재 요청에 대한 Accept-Encoding: 헤더의 내용. 예를 들면: 'gzip'.
- 'HTTP_ACCEPT_LANGUAGE'
- 현재 요청에 대한 Accept-Language: 헤더의 내용. 예를 들면: 'en'.
- 'HTTP_CONNECTION'
- 현재 요청에 대한 Connection: 헤더의 내용. 예를 들면: 'Keep-Alive'.
- 'HTTP_HOST'
- 현재 요청에 대한 Host: 헤더의 내용.
- 'HTTP_REFERER'
- 현재 페이지에 대한 유저 에이전트를 참조하는 페이지의 주소. 모든 에이전트가 이 값을 갖지 않는다. 일부 에이전트는 HTTP_REFERER를 각 특성에 맞게 변경하는 기능을 제공한다. 간단히 말해서, 이 값은 신뢰할수 없다.
- 'HTTP_USER_AGENT'
- 현재 요청에 대한 User-Agent: 헤더 내용. 이 값은 페이지에 접근 중인 유저 에이전트를 표시하는 문자열이다. 표준적인 예로는: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). get_browser()로 이 값을 사용하여 유저 에이전트의 능력에 맞게 페이지의 출력을 조절할수 있다.
- 'REMOTE_ADDR'
- 현재 페이지를 보고있는 유저의 IP 주소.
- 'REMOTE_HOST'
-
현재 페이지를 보고있는 유저의 호스트명. 역방향 dns 검색이
유저의 REMOTE_ADDR를 위해 사용된다.
Note: 웹서버는 이 변수를 생성할수 있도록 설정되어야 한다. 예를 들면 아파치에서는 httpd.conf안에서 HostnameLookups On 이 필요할것이다. gethostbyaddr()도 참고.
- 'REMOTE_PORT'
- 웹서버와 통신중인 유저 머신이 사용중인 포트.
- 'SCRIPT_FILENAME'
-
현재 수행되는 스크립트의 절대 경로명.
Note: file.php, ../file.php처럼 스크립트를 상대 경로로 지정하여 CLI로 실행할 경우, $_SERVER['SCRIPT_FILENAME']은 사용자가 지정한 상대 경로를 포함합니다.
- 'SERVER_ADMIN'
- 웹서버 설정 파일안의 SERVER_ADMIN (아파치용) 디렉티브에 주어지는 값. 스크립트가 가상 호스트에서 수행중이면, 이 값은 그 가상호스트를 위해 정의되는 값이 될것이다.
- 'SERVER_PORT'
- 웹서버가 통신을 위해 사용중인 서버 머신의 포트. 초기 설정값으로 '80';이 될것이다. 예를 들어, SSL을 사용중이면, 안전한 HTTP 포트로 정의된 어떤 값으로도 변경할수 있다.
- 'SERVER_SIGNATURE'
- 활설화되어있다면, 서버가 생성하는 페이지에 추가되는 서버 버전과 가상 호스트명을 갖는 문자열.
- 'PATH_TRANSLATED'
- 현재 스크립트에 대한 파일시스템(다큐먼트 루트가 아님) 기반의 경로 서버가 virtual-to-real 매핑으로 설정되면 보인다.
- 'SCRIPT_NAME'
- 현재 스크립트의 경로를 갖는다. 이 값은 가리킬 필요가 있는 페이지에 유용하다.
- 'REQUEST_URI'
- 이 페이지에 접근하기 위해 주어지는 URI; 예를 들면,'/index.html'.
- 'PHP_AUTH_USER'
- HTTP 인증을 사용하는 모듈로서 아파치에서 수행될때, 이 변수는 유저에 의해 제공되는 username으로 설정된다.
- 'PHP_AUTH_PW'
- HTTP 인증을 사용하는 모듈로서 아파치에서 수행될때, 이 변수는 유저가 제공하는 password로 설정된다.
- 'AUTH_TYPE'
- HTTP 인증을 사용하는 모듈로서 아파치에서 수행될때, 이 변수는 인증 타입으로 설정된다.
환경 변수: $_ENV
Note: 4.1.0부터 지원됨. 그 이전 버전에서는, $HTTP_ENV_VARS이 사용되었다.
이 변수들은 PHP 해석기가 실행중인 환경에서 PHP의 전역 네임스페이스로 포함된다. PHP가 실행중인 셀과 다른 종류의 셀을 수행하는 시스템에 의해서 많은 변수가 제공된다. 확정적인 변수 목록을 제공하는것은 불가능 하다. 선언된 환경변수 목록에 대한 셀의 문서를 참고하라.
다른 환경 변수는 CGI 변수를 포함한다. PHP가 서버 모듈로 실행중인지 또는 CGI 프로세서로 실행중인지에 따라 달라진다.
이변수는 '슈퍼전역', 도는 자동 전역, 변수이다. 이 말의 의미는 스크립트 내의 모든 영역에서 사용가능하다는 것이다. $HTTP_ENV_VARS를 사용할때와 마찬가지로, 함수나 메소드에서 이 변수에 접근하기 위해 global $_ENV;를 사용할 필요는 없다.
$HTTP_ENV_VARS는 동일한 초기치 정보를 갖는다. 그러나 자동전역이 아니다. (HTTP_ENV_VARS 와 $_ENV는 다른 변수이며 PHP가 따로 다루게 된다는 것에 주의한다)
register_globals 디렉티브가 설정되어있으면, 이변수는 스크립트의 전역 유효영역에서 사용가능해진다. 즉,$_ENV과 $HTTP_ENV_VARS 배열에서 독립적으로 사용된다. 관련 정보는, 전역 등록 사용하기라는 보안 챕터를 참고한다. 이들 각각의 전역변수는 자동전역이 아니다.
HTTP GET 변수: $_GET
Note: 4.1.0부터 지원됨. 이전 버전에서는 $HTTP_GET_VARS를 사용했슴.
HTTP GET 메소드를 통해 현재 스크립트에 전달되는 변수의 연관 배열. 어떤 영역에서는 자동으로 전역화된다.
이변수는 '슈퍼전역', 도는 자동 전역, 변수이다. 이 말의 의미는 스크립트 내의 모든 영역에서 사용가능하다는 것이다. $HTTP_GET_VARS를 사용할때와 마찬가지로, 함수나 메소드에서 이 변수에 접근하기 위해 global $_GET;를 사용할 필요는 없다.
$HTTP_GET_VARS는 동일한 초기치 정보를 갖는다. 그러나 자동전역이 아니다. (HTTP_GET_VARS 와 $_GET는 다른 변수이며 PHP가 따로 다루게 된다는 것에 주의한다)
register_globals 디렉티브가 설정되어있으면, 이변수는 스크립트의 전역 유효영역에서 사용가능해진다. 즉,$_GET와 $HTTP_GET_VARS 배열에서 독립적으로 사용된다. 관련 정보는, 전역 등록 사용하기라는 보안 챕터를 참고한다. 이들 각각의 전역변수는 자동전역이 아니다.
HTTP POST 변수: $_POST
Note: 4.1.0부터 지원됨. 이전 버전에서는 $HTTP_POST_VARS를 사용했슴.
HTTP POST 메소드를 통해 현재 스크립트에 전달되는 변수의 연관 배열. 어떤 영역에서는 자동으로 전역화된다.
이변수는 '슈퍼전역', 도는 자동 전역, 변수이다. 이 말의 의미는 스크립트 내의 모든 영역에서 사용가능하다는 것이다. $HTTP_POST_VARS를 사용할때와 마찬가지로, 함수나 메소드에서 이 변수에 접근하기 위해 global $_POST;를 사용할 필요는 없다.
$HTTP_POST_VARS는 동일한 초기치 정보를 갖는다. 그러나 자동전역이 아니다. (HTTP_POST_VARS 와 $_POST는 다른 변수이며 PHP가 따로 다루게 된다는 것에 주의한다)
register_globals 디렉티브가 설정되어있으면, 이변수는 스크립트의 전역 유효영역에서 사용가능해진다. 즉,$_POST와 $HTTP_POST_VARS 배열에서 독립적으로 사용된다. 관련 정보는, 전역 등록 사용하기라는 보안 챕터를 참고한다. 이들 각각의 전역변수는 자동전역이 아니다.
HTTP File 업로드 변수: $_FILES
Note: 4.1.0부터 지원됨. 이전 버전에서는 $HTTP_POST_FILES를 사용했슴.
HTTP POST 메소드를 통해 현재 스크립트에 업로드되는 아이템의 연관 배열. 어떤 영역에서는 자동으로 전역화된다.
이변수는 '슈퍼전역', 도는 자동 전역, 변수이다. 이 말의 의미는 스크립트 내의 모든 영역에서 사용가능하다는 것이다. $HTTP_POST_FILES를 사용할때와 마찬가지로, 함수나 메소드에서 이 변수에 접근하기 위해 global $_FILES;를 사용할 필요는 없다.
$HTTP_POST_FILES는 같은 정보를 갖고 있지만, 자동 전역 변수가 아니다.
register_globals 디렉티브가 설정되어있으면, 이변수는 스크립트의 전역 유효영역에서 사용가능해진다. 즉,$_FILES와 $HTTP_POST_FILES 배열에서 독립적으로 사용된다. 관련 정보는, 전역 등록 사용하기라는 보안 챕터를 참고한다. 이들 각각의 전역변수는 자동전역이 아니다.
Request 변수: $_REQUEST
Note: 4.1.0부터 지원됨. 이전 버전에서는 관련된 배열이 없다.
Note: PHP 4.3.0 이전에는 $_REQUEST 안에도 $_FILES 정보가 포함되어 있었다.
$_GET, $_POST, $_COOKIE의 내용물로 구성된 연관 배열.
이변수는 '슈퍼전역', 도는 자동 전역, 변수이다. 이 말의 의미는 스크립트 내의 모든 영역에서 사용가능하다는 것이다. 함수나 메소드에서 이 변수에 접근하기 위해 global $_REQUEST;를 사용할 필요는 없다.
register_globals 디렉티브가 설정되어있으면, 이변수는 스크립트의 전역 유효영역에서 사용가능해진다. 즉,$_REQUEST 배열에서 독립적으로 사용된다. 관련 정보는, 전역 등록 사용하기라는 보안 챕터를 참고한다. 이들 각각의 전역변수는 자동전역이 아니다.
세션 변수: $_SESSION
Note: 4.1.0부터 지원됨. 이전 버전에서는 $HTTP_SESSION_VARS를 사용했슴.
현재 스크립트에서 사용가능한 세션 변수를 포함하는 연관배열. 이 변수를 사용하는 방법에 대한 자세한 정보는 Session functions 문서를 참고.
이변수는 '슈퍼전역', 도는 자동 전역, 변수이다. 이 말의 의미는 스크립트 내의 모든 영역에서 사용가능하다는 것이다. $HTTP_SESSION_VARS를 사용할때와 마찬가지로, 함수나 메소드에서 이 변수에 접근하기 위해 global $_SESSION;를 사용할 필요는 없다.
$HTTP_SESSION_VARS는 같은 정보를 갖고 있지만, 자동 전역 변수가 아니다.
register_globals 디렉티브가 설정되어있으면, 이변수는 스크립트의 전역 유효영역에서 사용가능해진다. 즉,$_SESSION와 $HTTP_SESSION_FILES 배열에서 독립적으로 사용된다. 관련 정보는, 전역 등록 사용하기라는 보안 챕터를 참고한다. 이들 각각의 전역변수는 자동전역이 아니다.
Global 변수: $GLOBALS
Note: $GLOBALS PHP 3.0.0부터 지원되었다.
현재 스크립트의 전역 유효영역내에서 선언되어있는 모든변수에 대한 참조를 포함하는 연관배열이다. 변수명은 배열의 키로 사용된다.
이변수는 '슈퍼전역', 도는 자동 전역, 변수이다. 이 말의 의미는 스크립트 내의 모든 영역에서 사용가능하다는 것이다. 함수나 메소드에서 이 변수에 접근하기 위해 global $GLOBALS;를 사용할 필요는 없다.
이전 에러 메시지: $php_errormsg
$php_errormsg는 PHP에 의해 생성되는 가장 최근의 에러 메시지 텍스트를 포함하는 변수이다. 이변수는 에러가 발생한 영역내에서만 유효하다. 그리고, track_errors 설정 옵션이 on되어있어야 한다(초기값은 off이다)
기선언 변수
07-Apr-2008 09:15
18-Feb-2008 03:56
Note the manual entry for PHP_SELF states the following:
"The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar."
However I did some vigorous testing on three different machines and this note is not always true. The results are given below:
Given a URL of http://www.example.com/Info.php/Page/Home
Apache 2.2.4/Win32/PHP 5.2.2/Apache 2.0 Handler
----> PHP_SELF = Info.php/Page/Home
Apache 1.3.37/Unix/PHP 5.2.2/CGI
----> PHP_SELF = Info.php
Apache 1.3.33/Unix/5.1.4/FastCGI
----> PHP_SELF = Info.php
To be completely honest, I am not sure why this is the case; perhaps there is a setting in Apache to modify this option, but in either case take careful consideration of this note.
12-Feb-2008 06:15
I was a little frustrated by the fact that some of the _SERVER variables didn't seem to exist, so I did a bit of Googling and found the answer: many of these variables are supplied by the web server and not all web servers supply the same set of variables.
I found a comparison between Apache v1.3.29 and IIS v5.1 on this page: http://koivi.com/apache-iis-php-server-array.php Useful for those of us doing cross-platform development.
While running experiments with different browsers I noticed some of the HTTP_* variables come and go depending on the browser used, or in the case of Opera by diddling the "user mode" (the widget that lets you look at a page as text only, etc.). For example: in IE and Opera HTTP_KEEP_ALIVE was missing, but was present in Firefox and Mozilla, and when I fiddled with Opera's "user mode" I got somethings called HTTP_TE and HTTP_CACHE_CONTROL.
So, what you get is dependent on the web server AND the browser.
I did see one IIS supplied variable not on that list: REQUEST_TIME, which seems to be in Unix timestamp format.
While researching this I discovered there are plenty of people who have their phpinfo() page visible and indexed on a few search engines. For those who want to dig a bit deeper than that nice web page comparing Apache to IIS, looking at other peoples' phpinfo() pages could be useful. You get the version of PHP plus OS and web server they use, along with all the _SERVER variables. I found the highest percent of signal-to-noise by searching for "phpinfo()" (with the quotes) on Dogpile: http://www.dogpile.com/
13-Dec-2007 08:40
In addition to mfyahya at gmail dot com (2007-06-07 03:33):
If You are working with the Apache module mod_rewrite and want to set some environment vars, the Apache manual says this vars could be accessed in CGI using $ENV{VAR}. In PHP You might want to write $_ENV['VAR'] to get the value of VAR, but You have to access if via $_SERVER, and in some different ways:
1. Example: .htaccess and example.php
RewriteEngine on
RewriteRule ^?var1=([^;]*);var2=([^;]*)$ \
- [E=VAR1:$1,E=VAR2:$2]
<?php echo($_SERVER['VAR1']."\r\n"
.$_SERVER['VAR2']); ?>
2. Example: .htaccess and index.php
RewriteEngine on
RewriteRule ^index\.php$ - [L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
index.php [E=VAR1:$1,E=VAR2:$2]
<?php echo($_SERVER['REDIRECT_VAR1']."\r\n"
.$_SERVER['REDIRECT_VAR2']); ?>
Note: If any RewriteRule matches, an internal redirect than restarts (after the last defined rule, or immediately after the matched rule having a L-flag) checking the entire rule set again. For an internal redirect every defined VAR gets an 'REDIRECT_' prefix, i.e. VAR1 will be REDIRECT_VAR1, VAR2 will be REDIRECT_VAR2.
Of course, You can (additionally) redefine the original VAR:
RewriteEngine on
RewriteRule ^index\.php$ \
- [E=VAR1:%{REDIRECT_VAR1},E=VAR2:%{REDIRECT_VAR2},L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
index.php [E=VAR1:$1,E=VAR2:$2]
With this, You will have $_SERVER['REDIRECT_VAR*'] -and- $_SERVER['VAR*'].
***
The given examples are only for explanation, in any case they are not intended to fit Your needs. The "\<CRLF><SP>" in the .htaccess examples are only for display purpose, they should not occur in a real .htaccess file. The argument separator ';' in links can also be '&', but this may cause some trouble with HTML/XHTML. See the following pages for more information about this issue:
- http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2
- http://www.w3.org/QA/2005/04/php-session
22-Nov-2007 11:49
SECURITY RISK !
Never ever trust the values that comes from $_SERVER.
HTTP_X_FORWARDED, HTTP_X_FORWARDED_FOR, HTTP_FORWARDED_FOR, HTTP_FORWARDED, etc.. can be spoofed !
To get the ip of user, use only $_SERVER['REMOTE_ADDR'], otherwise the 'ip' of user can be easily changed by sending a HTTP_X_* header, so user can escape a ban or spoof a trusted ip.
Of course this is well know, but I don't see it mentioned in these notes..
If you use the ip only for tracking (not for any security features like banning or allow access to something by ip), you can also use HTTP_X_FORWARDED to get user's ip what are behind proxy.
14-Nov-2007 10:03
In response to mathiasrav's getip() implementation on 28-Jul-2007, it should be noted that it:
- assumes IPv4 addresses only
- returns $_SERVER['REMOTE_ADDR'] for any value of $_SERVER['HTTP_CLIENT_IP'] that matches 127.0.*.*, 192.168.*.* or 10.0.*.*, which is not desirable if you actually WANT the value of HTTP_CLIENT_IP
dlyaza's prior snippet has neither of these problems.
01-Nov-2007 07:59
Note that some headers will be checked for validity (by Apache, I suppose) before showing up in $_SERVER -- If-Modified-Since for example.
<?php
$lastmod = gmdate('D, d M Y H:i:s', filemtime('somefile'));
header("Last-Modified: $lastmod");
?>
This WON'T work, "GMT" is missing. Internet Explorer auto-fixes this by adding GMT, while Firefox resends this data as-is. (So an If-Modified-Since-header is sent, but neither shows up in $_SERVER nor in apache_request_headers()). This would be correct:
<?php
$lastmod = gmdate('D, d M Y H:i:s', filemtime('somefile')) . 'GMT';
header("Last-Modified: $lastmod");
?>
19-Oct-2007 12:39
@White-Gandalf: one can control this behavior by setting:
UseCanonicalName On|Off
in their apache config (at least, on *ix platforms).
On => $_SERVER['SERVER_NAME'] is the ServerName var from either the global server or virtual host, whichever wraps the PHP app closest.
Off => Whatever was in the Host: header sent by the client.
16-Oct-2007 07:01
'SERVER_NAME' does NOT necessarily refer to the name of a virtual host or any other things defined in the apache config.
Instead it simply takes the value of the "Host:" entry of the HTTP-header sent by the client.
At least with apache version 2.2.5 on Windows.
21-Sep-2007 08:45
The headers sent by the browser will be stored in the $_SERVER array -- they will get capitalized and prefixed with HTTP. So a header like "X-Foo-Bar: Baz" will result in <?php $_SERVER['HTTP_X_FOO_BAR'] = 'Baz';?>. This is why you should use isset before using e.g. HTTP_ACCEPT_LANGUAGE, 'cause it may not be set.
The only exception I know from that is HTTP_X_ORIGINAL_URI, which is always set and holds the current URL without querystring. But you can't trust that too because it can be overriden by sending a X-Original-URI header.
05-Aug-2007 09:41
To get the directory of the current script: (I think this is a little more resource-friendly, but then again with all the fast computers available, it does not matter so much...)
<?
// For the script that is running:
$script_directory = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], '/'));
// If your script is included from another script:
$included_directory = substr(__FILE__, 0, strrpos(__FILE__, '/'));
echo $script_directory . '<br />';
echo $included_directory . '<br />';
?>
If you have a script that only includes the script written above in a directory called 'includer', and I access it from a web browser, this will be what I see:
/path/to/includer/
/path/to/included/
11-Apr-2007 07:37
If you're working with $_GET a lot and need to preserve already set variables in a link for the next page, this function is pretty handy for simplifying the process of generating a new URL:
string setUrlVariables([string var, string value], [varN, valueN], ...)
<?php
function setUrlVariables() {
$arg = array();
$string = "?";
$vars = $_GET;
for ($i = 0; $i < func_num_args(); $i++)
$arg[func_get_arg($i)] = func_get_arg(++$i);
foreach (array_keys($arg) as $key)
$vars[$key] = $arg[$key];
foreach (array_keys($vars) as $key)
if ($vars[$key] != "") $string.= $key . "=" . $vars[$key] . "&";
if (SID != "" && SID != "SID" && $_GET["PHPSESSID"] == "")
$string.= htmlspecialchars(SID) . "&";
return htmlspecialchars(substr($string, 0, -1));
}
?>
You use it like this:
<a href="nextpage.php<?php echo setUrlVariables(); ?>">Link</a>
In this case setUrlVariables() will simply add all the $_GET variables of the current page/URL and even takes care of the PHPSESSID if you use one (and didn't change the default variable name). The above HREF would complete to e.g.:
"nextpage.php?var=21&PHPSESSID=BI89J"
If you supply arguments, do it like this:
<?php echo setUrlVariables("user", "foobar"); ?>
This would complete the HREF to e.g.:
"nextpage.php?user=foobar&var=21&PHPSESSID=BI89J"
Unsetting variables works by supplying an empty value:
<?php echo setUrlVariables("var", ""); ?>
"nextpage.php?user=foobar&PHPSESSID=BI89J"
setUrlVariables() also makes sure it produces "pretty URLs", so it doesn't output any unnecessary garbage. ;)
<?php
session_destroy();
echo setUrlVariables("user", "");
?>
"nextpage.php"
21-Mar-2007 01:22
If you have problems with $_SERVER['HTTPS'], especially if it returns no values at all you should check the results of phpinfo(). It might not be listed at all.
Here is a solution to check and change, if necessary, to ssl/https that will work in all cases:
<?php
if ($_SERVER['SERVER_PORT']!=443) {
$sslport=443; //whatever your ssl port is
$url = "https://". $_SERVER['SERVER_NAME'] . ":" . $sslport . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>
Of course, this should be done before any html tag or php echo/print.
24-Jan-2007 11:53
I think it is very important to note that PHP will automatically replace dots ('.') AND spaces (' ') with underscores ('_') in any incoming POST or GET (or REQUEST) variables.
This page notes the dot replacement, but not the space replacement:
http://us2.php.net/manual/en/language.variables.external.php
The reason is that '.' and ' ' are not valid characters to use in a variable name. This is confusing to many people, because most people use the format $_POST['name'] to access these values. In this case, the name is not used as a variable name but as an array index, in which those characters are valid.
However, if the register_globals directive is set, these names must be used as variable names. As of now, PHP converts the names for these variables before inserting them into the external variable arrays, unfortunately - rather than leaving them as they are for the arrays and changing the names only for the variables set by register_globals.
If you want to use:
<input name="title for page3.php" type="text">
The value you will get in your POST array, for isntance would be:
$_POST['title_for_page3_php']
18-Nov-2006 06:22
The *only* way to make Request_URI work as a 100% Apache-Compliant server variable on IIS/Windows is to use an Isapi Filter - as documented at http://neosmart.net/blog/archives/291 . The various steps mentioned below *completely* fail when a rewrite engine is employed, since IIS will *never* return a non-existent path (i.e. the actual pretty-URI used) via its server variables.
This also applies to accessing index.php via a folder.
For instance, calls made to /folder/ will appear as /folder/index.php and not /folder/.
The fix is to use the ISAPI filter provided at http://neosmart.net/blog/archives/291
You don't have to modify any of the actual scripts once this filter is in place - it automatically intercepts calls to REQUEST_URI and replaces them with the actual user-entered path.
09-Nov-2006 08:59
I'm sure this is elsewhere, but since 'chris dot chaudruc at gmail dot com' posted his example, I thought I would share a quick function I use to force HTTPS protocol on a page, without having to know the scripts name...
<?php
function ForceHTTPS()
{
if( $_SERVER['HTTPS'] != "on" )
{
$new_url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: $new_url");
exit;
}
}
?>
Correct me if part of this doesn't work right. I've always used *nix based servers for PHP, so I might not be aware of certain windows limitations. Thanks.
19-Sep-2006 02:16
If you want to use a form with multiple checkboxes (e.g. one per row) and assign the same name to each checkbox then the name needs to end with []. This tells PHP to put all checked values into an array variable.
For example:
<input type="checkbox" name="id[]" value="value_1">
<input type="checkbox" name="id[]" value="value_2">
..
<input type="checkbox" name="id[]" value="value_x">
You can now retrieve all values by using:
$values = $_POST['id'];
If the name does not end with [], then only a single value will be available via the $_POST variable even if the user checks several checkboxes.
05-May-2006 12:19
Refer to CanonicalName if you are not getting the ServerName in the $_SERVER[SERVER_NAME] variable....This was a pain to figure out for me...now it works as expected by turning canonical naming on.
http://www.apacheref.com/ref/http_core/UseCanonicalName.html
26-Apr-2006 07:24
Be careful with HTTP_HOST behind a proxy server. Use these instead.
[HTTP_X_FORWARDED_FOR]
[HTTP_X_FORWARDED_HOST]
[HTTP_X_FORWARDED_SERVER]
In my situation, I used [HTTP_X_FORWARDED_SERVER] in place of [HTTP_HOST] in order get the machine and hostname (www.myurl.com)
14-Apr-2006 06:18
So you have an application in your web space, with a URL such as this:
http://<host>/<installation_path>/
and pages such as
http://<host>/<installation_path>/subfolder1/subfolder2/page.php
You have a file called config.php in <installation_path> which is include()d by all pages (in subfolders or not).
How to work out <installation_path> without hard-coding it into a config file?
<?php
// this is config.php, and it is in <installation_path>
// it is included by <installation_path>/page.php
// it is included by <installation_path>/subfolder/page2.php
// etc
$_REAL_SCRIPT_DIR = realpath(dirname($_SERVER['SCRIPT_FILENAME'])); // filesystem path of this page's directory (page.php)
$_REAL_BASE_DIR = realpath(dirname(__FILE__)); // filesystem path of this file's directory (config.php)
$_MY_PATH_PART = substr( $_REAL_SCRIPT_DIR, strlen($_REAL_BASE_DIR)); // just the subfolder part between <installation_path> and the page
$INSTALLATION_PATH = $_MY_PATH_PART
? substr( dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($_MY_PATH_PART) )
: dirname($_SERVER['SCRIPT_NAME'])
; // we subtract the subfolder part from the end of <installation_path>, leaving us with just <installation_path> :)
?>
03-Apr-2006 02:11
To convert query string parameter values ($_GET, $_REQUEST), which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string (%uNNNN%uNNNN%uNNNN) fast and simple is to use PECL JSON extension:
function JavaScript_Unicode_URL_2_Str($js_uni_str) {
$res = preg_replace('/%u([[:alnum:]]{4})/', '\\u\1', $js_uni_str);
$res = str_replace('"', '\"', $res); // if in str "
$res = json_decode('["'.$res.'"]'); // JavaScrip array with string element
$res = $res[0];
$res = iconv('UTF-8', ini_get('default_charset'), $res);
return $res;
}
I was unable to convince my hosting company to change their installation of PHP and therefore had to find my own way to computer $_SERVER["DOCUMENT_ROOT"]. I eventually settled on the following, which is a combination of earlier notes (with some typos corrected):
<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
$_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
$_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>
30-Mar-2006 01:24
Note that PHP_SELF will not be equal to REQUEST_URI under Apache if mod_rewrite has been used to move one URL to another--PHP_SELF will contain the rewritten address, and REQUEST_URI will contain the URL the user sees in their browser.
07-Mar-2006 01:35
$_GET may not handle query string parameter values which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string.
To handle this the query parameter value can be obtained using a function such as:
function getQueryParameter ($strParam) {
$aParamList = explode('&', $_SERVER['QUERY_STRING']);
$i = 0;
while ($i < count($aParamList)) {
$aParam = split('=', $aParamList[$i]);
if ($strParam == $aParam[0]) {
return $aParam[1];
}
}
return "";
}
or by directly building an array or query string values and then processing the parameter string using a function such as the "unescape" function which can be found at http://www.kanolife.com/escape/2006/03/unicode-url-escapes-in-php.html (or http://www.kanolife.com/escape/ for related info).
28-Feb-2006 12:00
Note that it's a very, very bad idea to append to global variables in a loop, unless you really, really mean to do so in a global context. I just a while ago hung my server with a snippet of code like this:
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim($_SERVER['PHP_SELF'], "/\\");
$GLOBALS['SITE_ROOT'] = "http://$host$uri";
while ($i < somenumber)
readfile($GLOBALS['SITE_ROOT'] = $GLOBALS['SITE_ROOT'] . '/this/file.php');
$i++
}
?>
While it is an entertaining and unusual method of creating very long URLs and breaking servers, it's a pretty awesomely bad idea
(Especially considering that the script in question ran concurrently with others of it's type, so the value in $GLOBALS['SITE_ROOT'] was unknown.)
22-Feb-2006 08:05
Also on using IPs to look up country & city, note that what you get might not be entirely accurate. If their ISP is based in a different city or province/state, the IPs may be owned by the head office, and used across several areas.
You also have rarer situations where they might be SSHed into another server, on the road, at work, at a friend's... It's a nice idea, but as the example code shows, it should only be used to set defaults.
19-Jan-2006 08:05
The solution advanced by info at meshkaat dot com does not work correctly on machines with IIS configured to use
a virtual directory as the launch point. The address strings for $_SERVER['SCRIPT_FILENAME'] and $_SERVER['PHP_SELF'] will not necessarily have the same name for the highest level directory in $_SERVER['PHP_SELF'], and therefore this solution will not return the proper value.
11-Jan-2006 07:57
Under Windows XP SP2 and IIS, $_SERVER('x') returns a path using forward slash '/' as the separator, where x is:
PHP_SELF, SCRIPT_NAME
These arguments, however, all return a path using backward slash, '\' as the separator:
__FILE__, SCRIPT_FILENAME, and DOCUMENT_ROOT (if you use one of the methods mentioned previously).
Also note that if the name of the last directory in the document root includes a space, the methods described above for setting DOCUMENT_ROOT will return a value that drops the everything past the space.
30-Nov-2005 07:17
Since $_SERVER['DOCUMENT_ROOT'] is not always present, the following will provide it where $_SERVER dosen't.
<?php
function resolveDocumentRoot() {
$current_script = dirname($_SERVER['SCRIPT_NAME']);
$current_path = dirname($_SERVER['SCRIPT_FILENAME']);
/* work out how many folders we are away from document_root
by working out how many folders deep we are from the url.
this isn't fool proof */
$adjust = explode("/", $current_script);
$adjust = count($adjust)-1;
/* move up the path with ../ */
$traverse = str_repeat("../", $adjust);
$adjusted_path = sprintf("%s/%s", $current_path, $traverse);
/* real path expands the ../'s to the correct folder names */
return realpath($adjusted_path);
}
?>
It counts the number of folders down the path we are in the URL, then moves that number of folders up the current path... end result should be the document root :)
It wont work with virtual folders or in any situation where the folder in the URL dosen't map to a real folder on the disk (like when using rewrites).
11-Oct-2005 08:01
In response to tobias at net-clipping dot de
It is not an Apache bug. Please read http://httpd.apache.org/docs/2.1/mod/core.html#errordocument carefully (2.1 version here, 2.0 and 1.x is similar).
In short, if your ErrorDocument start with http:// Apache sends a redirect (302) to the error document, hence losing your original referer. If your ErrorDocument points to a relative path, 404 is maintained and so are your variables.
From the Apache manual:
"Note that when you specify an ErrorDocument that points to a remote URL (ie. anything with a method such as http in front of it), Apache will send a redirect to the client to tell it where to find the document, even if the document ends up being on the same server. This has several implications, the most important being that the client will not receive the original error status code, but instead will receive a redirect status code. This in turn can confuse web robots and other clients which try to determine if a URL is valid using the status code. In addition, if you use a remote URL in an ErrorDocument 401, the client will not know to prompt the user for a password since it will not receive the 401 status code. Therefore, if you use an ErrorDocument 401 directive then it must refer to a local document."
D.
30-Sep-2005 08:51
Re: You can take advantage of 404 error to an usable redirection using REQUEST_URI ...
Whilst this is effective, a line in the .htaccess such as:
RewriteEngine On
RewriteRule ^profiles/([A-Za-z0-9-]+) showprofile.php?profile=$1 [L,NC,QSA]
will throw the requested profile in a variable $profile to the showprofile.php page.
You can further enhance the url (e.g http://servername/profiles/Jerry/homeaddress/index.htm) and the second variable value homeaddress becomes available in $url_array[3] when used below $url_array=explode("/",$_SERVER['REQUEST_URI']);
Hope this helps - Works well for me
Drew
04-Aug-2005 08:55
Warning:
$_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME'] may not always be set correctly.
Some web hosts implement php as a CGI in such a way that they can turn it on or off for each virtual domain. Several $_SERVER and $_ENV variable values may be incorrect for documents in subdirectory subdomains of these virtual domains.
An include-file function or constant, instead of PHP_SELF or some other predefined variable throughout a website, will make it easier to "fix" an entire website in case something changes.
<?php
function true_url_path() {
// Pick the predefined variable that works on your server
return $_ENV['SCRIPT_URL'];
}
?>
Or
<?php
// Pick the predefined variable that works on your server
define("TRUE_URL_PATH", $_ENV['SCRIPT_URL']);
?>
31-Jul-2005 02:41
$_SERVER['QUERY_STRING']
Does not contain XHTML 1.1 compliant ampersands i.e. &
So you will need to do something like this if you are to use $_SERVER['QUERY_STRING'] in URL's.
// XHTML 1.1 compliant ampersands
$_SERVER['QUERY_STRING'] =
str_replace(array('&', '&'), array('&', '&'),
$_SERVER['QUERY_STRING']);
24-Jul-2005 06:59
Warning: $_SERVER['PHP_SELF'] can include arbitrary user input. The documentation should be updated to reflect this.
The request "http://example.com/info.php/attack%20here" will run /info.php, but in Apache $_SERVER['PHP_SELF'] will equal "/info.php/attack here". This is a feature, but it means that PHP_SELF must be treated as user input.
The attack string could contain urlencoded HTML and JavaScript (cross-site scripting) or it could contain urlencoded linebreaks (HTTP response-splitting).
The use of $_SERVER['SCRIPT_NAME'] is recommended instead.
15-Jul-2005 11:43
Note that $php_errormsg may contain a newline character. This can be problematic if you are trying to output it with a JavaScript "alert()" for example.
05-Jul-2005 06:22
I wanted to be able to embed a variable in the path. This is useful when, for example, images are rendered on the fly and you would like them to have different urls.
Here is an illustration:
www.somesite.com/image.php/IMAGETEXTHERE
This would return an image with the text after "image.php/" contained in it.
I could not recall the name of this feature, so I made a work-around in PHP...
<?
function getPathVariables() {
$sPathPS = $_SERVER[PHP_SELF];
$sPathFS = __FILE__;
$aPathPS = array_reverse(explode("/", $sPathPS));
$aPathFS = array_reverse(explode("/", $sPathFS));
$aImageArgs = array();
$x = 0;
while ( $aPathPS[$x] != $aPathFS[$x] && $aPathPS[$x] != $aPathFS[0] ) {
array_unshift($aImageArgs, $aPathPS[$x]) ;
$x++;
}
return $aImageArgs;
}
?>
This function will return an array containing each "/" delimited portion of the path after the script name itself.
27-Jun-2005 07:14
Note that $_SERVER['QUERY_STRING'] behaves differently under IIS/Apache.
In Apache (at least on Windows) it is ALWAYS set - if no query string was specified in the URL, $_SERVER['QUERY_STRING'] is initialised as an empty string.
In IIS, if no query string is included in the URL, $_SERVER['QUERY_STRING'] is NOT SET, so trying to access it without checking for its existence will generate notices.
13-Jun-2005 01:03
A note about the QUERY_STRING variable when using IIS:
I have found that IIS does not handle large query strings gracefully when passed from PHP. In addition to truncating them to around 1024 kb, I have seen IIS actually add data from other server variables to the end of the truncated data.
This occurred on Windows 2000 server running IIS 5.0 and PHP 4.3.8. The problem did not occur when handled by Apache, even on another Windows server.
Note: I realize passing this much data is best accomplished using the POST method, which would avoid this problem all together. I'm merely detailing a problem that I came across.
I have created a page that includes the (very long) query string that was used and some of the results that I saw while testing. It can be viewed at http://www.csb7.com/test/php_iis_qs_limit/. I didn't want to include it here as it would stretch the page out significantly.
~Chris Bloom
07-Jun-2005 06:33
If you use Apache's redirection features for custom error pages or whatever, the following Apache's REDIRECT variables are also available in $_SERVER:
$_SERVER['REDIRECT_UNIQUE_ID]'
$_SERVER['REDIRECT_SCRIPT_URL]'
$_SERVER['REDIRECT_SCRIPT_URI]'
$_SERVER['REDIRECT_SITE_ROOT]'
$_SERVER['REDIRECT_SITE_HTMLROOT]'
$_SERVER['REDIRECT_SITE_CGIROOT]'
$_SERVER['REDIRECT_STATUS]'
$_SERVER['REDIRECT_QUERY_STRING]'
$_SERVER['REDIRECT_URL]'
I'm not sure if this is a complete list though
06-May-2005 11:23
With the arrival of the Google Web Accelerator, the problem of keeping track of users through $_SERVER['REMOTE_ADDR'] (for a much shorter while than with cookies) has reared its ugly head anew.
For those confronted with this issue, remember that Google implements the $_SERVER['HTTP_X_FORWARDED_FOR'] header giving the IP address of the connection that it proxies.
Hope this helps...
13-Apr-2005 06:23
Under Windows 2000, running IIS and PHP 4.3.10, $_SERVER['SCRIPT_NAME'] is not available, however $_SERVER['SCRIPT_FILENAME'] is present and seems to contain the same information.
Matt Johnson says that one should never urldecode() $_GET data. This is incorrect.
If magic_quotes_gpc is turned off in php.ini, then you *do* need to urldecode() $_GET data.
Having magic_quotes_gpc turned off is considered good practise.
13-Feb-2005 04:19
The Environment variable $ENV is useful for coding portable platform specific application constants.
// Define a Windows or else Linux root directory path
$_ENV['OS'] == 'Windows_NT' ? $path = 'L:\\www\\' : $path = ' /var/www/';
define('PATH', $path);
echo PATH;
11-Feb-2005 07:09
Sorry if this is old news to some, but it might not be obvious at a first glance:
If you are using $_SERVER['remote_addr'] as a way to keep track of a logged-in user (this can be useful to avoid several types of hacking), remember that it might not be the user's actual IP address!
I was trying to implement a login feature that used this, storing the IP into a DB. It went smoothly while on a LAN, but wrecked havoc when accepting outter connections.
26-Jan-2005 12:51
If your having problems returning $_SERVER variables using apache, be sure you enable:
ExtendedStatus On
in your httpd.conf file.
If it's off, then things like $_SERVER['HTTP_HOST'] won't be present.
23-Jan-2005 04:02
The variable $php_errormsg is not populated if you have XDebug running.
09-Jan-2005 01:26
Running Xitami in Windows 2000 and PHP 4.3.7, nor PHP_SELF or SCRIPT_FILENAME is not availiable. Trying SCRIPT_NAME instead. Here is a function that returns the filename of a script without slashes. Good for use in HTML FORM ACTION=""-arguments...
function getThisFile() {
/* try to use PHP_SELF first... */
if (!empty($_SERVER['PHP_SELF'])) {
$strScript = $_SERVER['PHP_SELF'];
/* otherwise, try SCRIPT_NAME */
} else if (!empty($_SERVER['SCRIPT_NAME'])) {
$strScript = @$_SERVER['SCRIPT_NAME'];
/* last resort - quit out and return nothing */
} else {
return null;
}
/* fint last frontslash in filename */
$intLastSlash = strrpos($strScript, "/");
/* check if last backslash is more far away in filename */
if (strrpos($strScript, "\\")>$intLastSlash) {
/* if so, use the backslash position instead */
$intLastSlash = strrpos($strScript, "\\");
}
/* cut out from the last slash and to the end of the filename */
return substr($strScript, $intLastSlash+1, strlen($strScript));
}
Tested on PHP 4.3.7/Win32 and PHP 5.0.3/Linux.
You may add more filepaths to the first if-section
to get more chances to catch up the filename if you can.
25-Dec-2004 04:50
A reminder: if you are considering using urldecode() on a $_GET variable, DON'T!
Evil PHP:
<?php
# BAD CODE! DO NOT USE!
$term = urldecode($_GET['sterm']);
?>
Good PHP:
<?php
$term = $_GET['sterm'];
?>
The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you!
Using urldecode() on $_GET can lead to extreme badness, PARTICULARLY when you are assuming "magic quotes" on GET is protecting you against quoting.
Hint: script.php?sterm=%2527 [...]
PHP "receives" this as %27, which your urldecode() will convert to "'" (the singlequote). This may be CATASTROPHIC when injecting into SQL or some PHP functions relying on escaped quotes -- magic quotes rightly cannot detect this and will not protect you!
This "common error" is one of the underlying causes of the Santy.A worm which affects phpBB < 2.0.11.
19-Oct-2004 08:13
Nothing about the message-body ...
You can get cookies, session variables, headers, the request-uri , the request method, etc but not the message body. You may want it sometimes when your page is to be requested with the POST method.
Maybe they should have mentioned $HTTP_RAW_POST_DATA or php://stdin
06-Sep-2004 12:21
Using Apache/mod_ssl, there are further environment variables available to check for an SSL connection (can be more useful than $_SERVER['SERVER_PORT']), documented here: http://www.modssl.org/docs/2.8/ssl_reference.html#ToC25
To test whether the client connected with SSL I can use $_SERVER['HTTPS'] e.g (with redirect to secured, current URL);
<?php
if ( !isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' ) {
header ('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit();
}
?>
30-Aug-2004 07:13
You can add $_SERVER["DOCUMENT_ROOT"] to IIS by editing the Environment Variables of your Windows server (was tested on WinXP SP2).
Right click on My Computer >> Properties >> Advanced.
In the System variables click on 'New' and Type in the name field 'DOCUMENT_ROOT' and in the value field the path to your IIS document root folder.
Don't forget to restart your Windows (IIS restart won't load the new settings).
12-May-2004 05:34
$_SERVER['DOCUMENT_ROOT'] *is* supported by IIS, although only when running PHP as an ISAPI module.
05-Apr-2004 09:20
Be carful when using $_SERVER['DOCUMENT_ROOT']; in your applications where you want to distribute them to other people with different server types. It isnt always supported by the webserver (IIS).
18-Dec-2003 09:32
The RAW / uninterpreted HTTP POst information can be accessed with:
$GLOBALS['HTTP_RAW_POST_DATA']
This is useful in cases where the post Content-Type is not something PHP understands (such as text/xml).
03-Dec-2003 03:54
Running PHP 4.3 under IIS 5 on Windows XP, there is no $_SERVER['REQUEST_URI'] variable. This seems to fix it:
if(!isset($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1);
}
