Portable and safe way to get PATH_INFO

后端 未结 6 2040
青春惊慌失措
青春惊慌失措 2021-01-05 04:56

I\'m seeking a portable way to receive the (handy) $_SERVER[\'PATH_INFO\'] variable.

After reading a while, it turns out PATH_INFO

6条回答
  •  日久生厌
    2021-01-05 05:17

    It depends on the definitions for "portable" and "safe".

    Let me see if I understood:

    1) You are not interested on CLI:

    • you mentioned PHP/CGI
    • PATH_INFO is a piece of an URL; so, it only makes sense to discuss PATH_INFO when the script is accessed from a URL (i.e. from an HTTP connection, usually requested by a browser)

    2) You want to have PATH_INFO in all OS + HTTP server + PHP combination:

    • OS may be Windows, Linux, etc
    • HTTP server may be Apache 1, Apache 2, NginX, Lighttpd, etc.
    • PHP may be version 4, 5, 6 or any version

    Hmmm... PHP_INFO, in the $_SERVER array, is provided by PHP to a script in execution only under certain conditions, depending on the softwares mentioned above. It is not always available. The same is true for the entire $_SERVER array!

    In short: "$_SERVER depends on the server"... so a portable solution can't relay on $_SERVER... (just to give one example: we have a tutorial to set up PHP/CGI $_SERVER variables on NginX HTTP server at kbeezie.com/view/php-self-path-nginx/)

    3) Despite what was mentioned above, it worths mentioning that if we somehow have the full URL that was requested available as a string, it is possible to obtain the PATH_INFO from it by applying regular expressions and other PHP string functions, safely (also validating the input string as a valid URI).

    So, provided that we have the URL string... then YES, WE HAVE a portable and safe way to determine PATH_INFO from it.


    Now, we have two clear and focused implementation issues:

    1. How to obtain the URL?
    2. How to obtain the PATH_INFO from the URL?

    Among several possibilities, here is a possible approach:

    How to obtain the URL?

    1) With your deep and comprehensive knowledge about each HTTP server + OS + PHP version combination, check and try each possibility to obtain the URL from the $_SERVER array (verify 'PHP_SELF', 'QUERY_STRING', 'SCRIPT_FILENAME', 'PATH_TRANSLATED', 'SCRIPT_NAME', 'REQUEST_URI', 'PATH_INFO', 'ORIG_PATH_INFO', 'HTTP_HOST', 'DOCUMENT_ROOT' or whatever)

    2) If previous step failed, make the PHP script return a javascript code that sends "document.URL" information back. (The portability issue transfered to client-side.)

    How to obtain the PATH_INFO from the URL?

    This code linked here does this.

    This is my humble opinion and approach to the problem.

    What do you think?

提交回复
热议问题