$_SERVER array in PHP is very useful in getting lot of information about the PHP script in execution as well as the server/request details. $_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.
Following are few very useful attributes of $_SERVER array:
This is 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. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. However, unlike $_SERVER[‘SCRIPT_NAME’], it provides additional path information like $_SERVER[‘REQUEST_URI’] when the actual php file is present in the path. So when the $_SERVER[‘REQUEST_URI’] is /index.php/big/directory/ then $_SERVER[‘PHP_SELF’] will be /index.php/big/directory/.
However if all the URI’s under http://www.example.com/ is mapped to http://www.example.com/index.php, then, for example, http://www.example.com/abc/def will return /index.php like $_SERVER[‘SCRIPT_NAME’]. Note that $_SERVER[‘REQUEST_URI’] data is ignored for this request.
$_SERVER[‘PHP_SELF’] is supported on all platforms.
Gives you the IP address of server on which the current script is executing. Thus for printing IP address of server use following code snippet.
<?php echo "Server IP Address is $_SERVER['SERVER_ADDR']" ?>
$_SERVER[‘REMOTE_ADDR’] returns the IP address from which the user is viewing the current page. REMOTE_ADDR will not written correct IP address if the client is behind a proxy. In that case use the script mention in this tutorial: PHP Code Snippet
The actual URI used in HTTP protocol (after GET or POST) to make the request. For example if you access this site with the following command:
GET / HTTP/1.0
Then $_SERVER[‘REQUEST_URI’] will be /.
However is you access the same page using:
GET /index.php HTTP/1.0
Then $_SERVER[‘REQUEST_URI’] will be
Although $_SERVER[‘SCRIPT_NAME’] and $_SERVER[‘PHP_SELF’] will be /index.php in both cases. $_SERVER[‘REQUEST_URI’] is not supported on IIS (with or without SSL).
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).