Search code examples
phpwebserverapache2global-variables

PHP $_SERVER variable to identify file requested


In the PHP $_SERVER variable, four variables reference the file requested.:

["SCRIPT_FILENAME"]=>   string(21) "/webroot/file.php"
["REQUEST_URI"]=>       string(9) "/file.php?param=valyou"
["SCRIPT_NAME"]=>       string(9) "/file.php"
["PHP_SELF"]=>          string(9) "/file.php"

Would/Could any of these array members not refer to the actual file requested via URL? For example, URL rewriting, which I don't have experience with or plan on using for this project.

I notice "REQUEST_URI" also includes GET variables, which I don't need.


Solution

  • If you need the actual file being requested then you should use SCRIPT_FILENAME (absolute filesystem path) or SCRIPT_NAME (root-relative filesystem path) or ...the magic constant __FILE__ for the current script being executed (but this isn't necessarily the file being requested by the user).

    Would/Could any of these array members not refer to the actual file requested via URL?

    Yes.

    Whilst PHP_SELF refers to the requested file, it can also include additional pathname information (PATH_INFO) from the URL. eg. /file.php/foo/bar.

    REQUEST_URI is the URL being requested, so this can be completely different. Only when the requested URL directly maps to a filesystem path do these look similar. For example, if the URL /foo internally rewrites to /file.php then REQUEST_URI holds /foo, not /file.php.