PHP $_SERVER : Obtaining Server and Environment Information

The php $_SERVER array is a super global that contains information about the server and environment that the php script is running in. Within this array there are 3 indexes or values that behave similarly and it is often hard to know which one to utilize. They are:

  • $_SERVER[ ‘PHP_SELF’ ]
  • $_SERVER[ ‘SCRIPT_NAME’ ]
  • $_SERVER[ ‘REQUEST_URI’ ]

To compare these variables lest look at the following 4 requests made to the same script

  • 1 : Default file in folder
    http://www.example.com/projects/
  • 2 : Direct script access
    http://www.example.com/projects/index.php
  • 3 : Script access with variables
    http://www.example.com/projects/index.php?categroy=12&id=263
  • 4 : Script access with appended directories
    http://www.example.com/projects/index.php/test/medium/

PHP_SELF

The PHP_SELF index contains the file name of the script currently executing in relation to the document root of the server it is being run on. What this means is taht for all cases except for 4 /projects/index.php will be returned. In the case where directories are appended they will get displayed by PHP_SELF and /projects/index.php/test/medium/ would be returned.

SCRIPT_NAME

The SCRIPT_NAME index like PHP_SELF is used to return the name of the executing script in relation to the document root. The one difference is that regardless of appended directories or query parameters the file is always returned the same as /projects/index.php

REQUEST_URI

The REQUEST_URI index is used to obtain the exact request that was requested from the server. This includes any query parameters or appended directories. So for each request everything after the root would be returned:

  • /projects/
  • /projects/index.php
  • /projects/index.php?categroy=12&id=263
  • /projects/index.php/test/medium/

For a full explanation of the various indices of the $_SERVER super global please visit the PHP Manual.

Resources

ex

// PHP //

Comments & Questions

Add Your Comment