difference between $_SERVER[‘REQUEST_URI’], $_SERVER[‘PHP_SELF’], and __FILE__

$_SERVER[‘REQUEST_URI’] is what you type in your address bar of  your browse(no protocol and host part).

$_SERVER[‘PHP_SELF’] is the url of the first file loaded(no protocol and host part) with query parameters stripped. Even $_SERVER[‘REQUEST_URI’] has no query parameter, $_SERVER[‘PHP_SELF’] is not necessarily equal to $_SERVER[‘REQUEST_URI’]. For example if you use rewrite rule in .htaccess, $_SERVER[‘REQUEST_URI’] would be the url before rewrite while $_SERVER[‘PHP_SELF’] is the url after rewrite.

__FILE__ is the path name of current file. If current file is included in another file, $_SERVER[‘PHP_SELF’] is still the url of the first loaded file while __FILE__ changes to the current file.

Things get complicated if the url has something more(besides the query parameters) beyond the handling script(Apache can find the script even the script’s file name is not the end part of the url). For example, when a non-existing url is redirected to the current script, e.g., http://myprogrammingnotes.com/some-non-existingurl is redirected to http://myprogrammingnotes.com/index.php/some-non-existingurl. In this case, $_SERVER[‘PHP_SELF’] is http://myprogrammingnotes.com/index.php/some-non-existingurl,i.e., the stuff after redirection, not the php file itself(http://myprogrammingnotes.com/index.php). So how can we get the url of the current php file itself? The answer is using $_SERVER[‘SCRIPT_NAME’] which returns /index.php. Using __FILE__ with some coding is also possible to retrieve the current script but not very convenient because __FILE__ returns the file system path name not url.

Posted in

Leave a Reply