Predefined Variables
Since PHP 4.1.0, the preferred method for retrieving external variables is with the superglobals mentioned below. Before this time, people relied on either register_globals or the long predefined PHP arrays ($HTTP_*_VARS). Начиная с PHP 5.0.0, длинные предопределенные переменные массивов PHP могут быть отключены директивой register_long_arrays.
Server variables: $_SERVER
Замечание: Introduced in 4.1.0. In earlier versions, use $HTTP_SERVER_VARS.
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI 1.1 specification, so you should be able to expect those.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SERVER; to access it within functions or methods, as you do with $HTTP_SERVER_VARS.
$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SERVER and $HTTP_SERVER_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.
You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.
- 'PHP_SELF'
- 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. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
- 'argv'
- Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
- 'argc'
- Contains the number of command line parameters passed to the script (if run on the command line).
- 'GATEWAY_INTERFACE'
- What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
- 'SERVER_ADDR'
- The IP address of the server under which the current script is executing.
- 'SERVER_NAME'
- The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
- 'SERVER_SOFTWARE'
- Server identification string, given in the headers when responding to requests.
- 'SERVER_PROTOCOL'
- Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
- 'REQUEST_METHOD'
-
Which request method was used to access the page; i.e. 'GET',
'HEAD', 'POST', 'PUT'.
Замечание: PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.
- 'REQUEST_TIME'
- The timestamp of the start of the request. Available since PHP 5.1.0.
- 'QUERY_STRING'
- The query string, if any, via which the page was accessed.
- 'DOCUMENT_ROOT'
- The document root directory under which the current script is executing, as defined in the server's configuration file.
- 'HTTP_ACCEPT'
- Contents of the Accept: header from the current request, if there is one.
- 'HTTP_ACCEPT_CHARSET'
- Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
- 'HTTP_ACCEPT_ENCODING'
- Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
- 'HTTP_ACCEPT_LANGUAGE'
- Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
- 'HTTP_CONNECTION'
- Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
- 'HTTP_HOST'
- Contents of the Host: header from the current request, if there is one.
- 'HTTP_REFERER'
- The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
- 'HTTP_USER_AGENT'
- Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
- 'HTTPS'
- Set to a non-empty value if the script was queried through the HTTPS protocol. Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.
- 'REMOTE_ADDR'
- The IP address from which the user is viewing the current page.
- 'REMOTE_HOST'
-
The Host name from which the user is viewing the current
page. The reverse dns lookup is based off the
REMOTE_ADDR of the user.
Замечание: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().
- 'REMOTE_PORT'
- The port being used on the user's machine to communicate with the web server.
- 'SCRIPT_FILENAME'
-
The absolute pathname of the currently executing script.
Замечание: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
- 'SERVER_ADMIN'
- The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
- 'SERVER_PORT'
- The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
- 'SERVER_SIGNATURE'
- String containing the server version and virtual host name which are added to server-generated pages, if enabled.
- 'PATH_TRANSLATED'
-
Filesystem- (not document root-) based path to the current
script, after the server has done any virtual-to-real
mapping.
Замечание: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.
- 'SCRIPT_NAME'
- Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
- 'REQUEST_URI'
- The URI which was given in order to access this page; for instance, '/index.html'.
- 'PHP_AUTH_DIGEST'
- When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
- 'PHP_AUTH_USER'
- When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
- 'PHP_AUTH_PW'
- When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.
- 'AUTH_TYPE'
- When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.
Environment variables: $_ENV
Замечание: Introduced in 4.1.0. In earlier versions, use $HTTP_ENV_VARS.
These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.
Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_ENV; to access it within functions or methods, as you do with $HTTP_ENV_VARS.
$HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_ENV and $HTTP_ENV_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.
HTTP GET variables: $_GET
Замечание: Introduced in 4.1.0. In earlier versions, use $HTTP_GET_VARS.
An associative array of variables passed to the current script via the HTTP GET method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_GET; to access it within functions or methods, as you do with $HTTP_GET_VARS.
$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_GET and $HTTP_GET_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.
HTTP POST variables: $_POST
Замечание: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_VARS.
An associative array of variables passed to the current script via the HTTP POST method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_POST; to access it within functions or methods, as you do with $HTTP_POST_VARS.
$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_POST and $HTTP_POST_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.
HTTP File upload variables: $_FILES
Замечание: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_FILES.
An associative array of items uploaded to the current script via the HTTP POST method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_FILES; to access it within functions or methods, as you do with $HTTP_POST_FILES.
$HTTP_POST_FILES contains the same information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_FILES and $HTTP_POST_FILES arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.
Request variables: $_REQUEST
Замечание: Introduced in 4.1.0. There is no equivalent array in earlier versions.
Замечание: Prior to PHP 4.3.0, $_FILES information was also included in $_REQUEST.
An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_REQUEST; to access it within functions or methods.
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_REQUEST array. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.
Session variables: $_SESSION
Замечание: Introduced in 4.1.0. In earlier versions, use $HTTP_SESSION_VARS.
An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SESSION; to access it within functions or methods, as you do with $HTTP_SESSION_VARS.
$HTTP_SESSION_VARS contains the same information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SESSION and $HTTP_SESSION_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not superglobals.
Global variables: $GLOBALS
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $GLOBALS; to access it within functions or methods.
The previous error message: $php_errormsg
$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).
Raw POST data: $HTTP_RAW_POST_DATA
$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data
HTTP response headers: $http_response_header
The $http_response_header array is similiar to the get_headers() function. When using the HTTP wrapper $http_response_header will be populated with the HTTP response headers.
Коментарии
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).
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
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;
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
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.
$_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']);
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
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.
$_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).
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']) ) );
?>
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> :)
?>
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
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']
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.
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.
I use HTTP_X_FORWARDED_FOR because my webserver is behind a reverse proxy.
This can be made secure:
Configure the reverse proxy to block this field, and override it correctly.
Configure the apache server to only accept incoming connections from the reverse proxy.