Home >Backend Development >PHP Tutorial >What are the differences between PHP_SELF, PATH_INFO, SCRIPT_NAME, and REQUEST_URI and which one should I use?
When developing server-side applications, determining the request's exact address is crucial for navigation and handling. This article compares four PHP superglobals: PHP_SELF, PATH_INFO, SCRIPT_NAME, and REQUEST_URI, to provide a clear understanding of their differences and reliability.
PHP_SELF represents the current script being executed. Its value includes the script's full URI, including any subdirectories or query strings. In the example provided, where mod_rewrite is used to route requests to a main controller, PHP_SELF will always be "index.php," regardless of the actual requested URL.
PATH_INFO contains the portion of the URI following the script name and any query string. It represents the path information relative to the script. Using the same example, if the requested URL is "http://www.example.com/faq/whatever," PATH_INFO will hold "/faq/whatever."
SCRIPT_NAME gives the complete path and filename of the currently running script. In most cases, it is similar to PHP_SELF, but differs when using mod_rewrite with RewriteBase or if the request is a subrequest. In the mod_rewrite example, SCRIPT_NAME will be "/test.php" instead of "index.php."
REQUEST_URI contains the complete URI as sent by the client, including any query string. It is the most complete representation of the requested URL. However, it can differ from SCRIPT_NAME and PHP_SELF under specific conditions, such as non-empty query strings, server-side redirections, or HTTP errors (e.g., 404).
The following examples illustrate the differences between these superglobals:
When requested URL is in form "http://example.com/test.php/foo/bar":
When non-empty query string is entered (http://example.com/test.php?foo=bar):
When server-side redirection is in effect:
Based on these examples, REQUEST_URI provides the most comprehensive representation of the requested URL. However, it can be affected by server-side redirections or HTTP errors. PHP_SELF and SCRIPT_NAME are generally reliable for determining the script's address, but PATH_INFO can be useful for extracting specific path information when mod_rewrite is used.
The above is the detailed content of What are the differences between PHP_SELF, PATH_INFO, SCRIPT_NAME, and REQUEST_URI and which one should I use?. For more information, please follow other related articles on the PHP Chinese website!