_server request method in php

[PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8]

$_SERVERServer and execution environment information

Description

$_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.

Indices

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 //example.com/foo/bar.php would be /foo/bar.php. 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. '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; e.g. '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.

Note: Under Apache 2, you must set UseCanonicalName = On and ServerName. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.

'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; e.g. 'HTTP/1.0'; 'REQUEST_METHOD' Which request method was used to access the page; e.g. 'GET', 'HEAD', 'POST', 'PUT'.

Note:

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. 'REQUEST_TIME_FLOAT' The timestamp of the start of the request, with microsecond precision. '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. '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 on the REMOTE_ADDR of the user.

Note: 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. 'REMOTE_USER' The authenticated user. 'REDIRECT_REMOTE_USER' The authenticated user if the request is internally redirected. 'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Note:

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.

Note: Under the Apache 2, you must set UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On in order to get the physical [real] port, otherwise, this value can be spoofed and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.

'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.

Note: 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 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 doing HTTP authentication this variable is set to the username provided by the user. 'PHP_AUTH_PW' When doing HTTP authentication this variable is set to the password provided by the user. 'AUTH_TYPE' When doing HTTP authentication this variable is set to the authentication type. 'PATH_INFO' Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL //www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff. 'ORIG_PATH_INFO' Original version of 'PATH_INFO' before processed by PHP.

Examples

Example #1 $_SERVER example

The above example will output something similar to:

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Vladimir Kornea

13 years ago

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:

Example.com

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 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 at tiscali dot it

2 years ago

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.

pierstoval at example dot com

5 years ago

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 [ //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...]

Lord Mac

12 years ago

An even *more* improved version...

sammyhacker at gmail dot com

1 year ago

To put it simply, $_SERVER contains all the environment variables.

CGI works by an HTTP application server filling in all the required environment variables and invoking the PHP process. And these environment variables are stored under $_SERVER.

MarkAgius at markagius dot co dot uk

11 years ago

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


$host will finally contain the absolute path.

Mark Simon

3 years ago

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:

Richard York

13 years ago

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]
  }

DanielTahar

2 years ago

To expand a bit on the price you could pay for relying on 'HTTP_REFERER': several large news sites I read often have paywalls, with cookies in place so you can only read X articles before you must subscribe; if using Incognito, they count the number of times you accessed via the same IP; everything to get you to subscribe. However, in order to be appealing, any visit where the 'HTTP_REFERER' is Google News will give you the entire article. I'm sure it's a dilemma their webmasters have, but for now any time someone sends you a story on one of them, all you have to do is search for the title and click the result from Google News. Bottom line: never count on it.

PS [1]: ofcourse i'm talking about a friend. I pay for content.
PS [2]: after some debate, the RFC decided to keep 'HTTP_REFERER', although it's misspelled.

chris at ocproducts dot com

5 years ago

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

Tom

10 years ago

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.

picov at e-link dot it

10 years ago

A simple function to detect if the current page address was rewritten by mod_rewrite:

jarrod at squarecrow dot com

13 years ago

$_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:



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].

pomat at live dot it

9 years ago

$_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:



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:



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'].

centurianii at yahoo dot co dot uk

5 years ago

If you apply redirection in ALL your requests using commands at the Apache virtual host file like:
RewriteEngine On
RewriteCond "%{REQUEST_URI}" "!=/index.php"
RewriteRule "^/[.*]$" "index.php?$1" [NC,NE,L,QSA]
you should expect some deviations in your $_SERVER global.

Say, you send a url of: [hostname here]/a/b?x=1&y=2
which makes Apache to modify to: /index.php?/a/b?x=1&y=2

Now your $_SERVER global contains among others:
'REQUEST_URI' => '/a/b?x=1&y=2', it retains the initial url after the host
'QUERY_STRING' => 'a/b&x=1&y=2', notice how php replaces '?' with '&'
'SCRIPT_NAME' => '/index.php', as it was intended to be.

To test your $_SERVER global:
function serverArray[]{
   $arr = array[];
   foreach[$_SERVER as $key=>$value]
      $arr[] = '   \'' . $key . '\' => \'' . [isset[$value]? $value : '-'] . '\'';
   return @\sort[$arr]? '$_SERVER = array[
' . implode[$arr, ',
'] . '
];' : false;
}
echo serverArray[];

info at mtprod dot com

13 years ago

On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.

php at isnoop dot net

12 years ago

Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"

pudding06 at gmail dot com

13 years ago

Here's a simple, quick but effective way to block unwanted external visitors to your local server:



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.

lilJoshu

3 years ago

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.

jit_chavan at yahoo dot com

8 years ago

searched $_SERVER["REDIRECT_URL"] for a while and noted that it is not mentioned in php documentation page itself. look like this is only generated by apache server[not others] and using   $_SERVER["REQUEST_URI"] will be useful in some cases as mine.

mirko dot steiner at slashdevslashnull dot de

12 years ago

Chủ Đề