Programing

PHP_SELF 대 PATH_INFO 대 SCRIPT_NAME 대 REQUEST_URI

crosscheck 2020. 8. 20. 07:37
반응형

PHP_SELF 대 PATH_INFO 대 SCRIPT_NAME 대 REQUEST_URI


CodeIgniter에서 PHP 애플리케이션을 구축하고 있습니다. CodeIgniter는 모든 요청을 메인 컨트롤러로 보냅니다 : index.php. 그러나 나는 index.phpURI에서 보고 싶지 않습니다 . 예를 들어 http://www.example.com/faq/whatever는로 라우팅됩니다 http://www.example.com/index.php/faq/whatever. 스크립트가 주소가 무엇인지 알 수있는 신뢰할 수있는 방법이 필요하므로 탐색으로 무엇을해야하는지 알 수 있습니다. mod_rewriteCodeIgniter 문서에 따라을 사용했습니다 .

규칙은 다음과 같습니다.

RewriteEngine on
RewriteCond $1 !^(images|inc|favicon\.ico|index\.php|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L] 

일반적으로 나는 단지 확인 php_self하지만이 경우에는 항상 index.php입니다. 나는에서 그것을 얻을 수 REQUEST_URI, PATH_INFO등,하지만 난 가장 신뢰할 수있을 것입니다 결정하기 위해 노력하고있어. 사람의 노하우를합니까 (또는 어디에서 찾을 알고) 사이의 진정한 차이 PHP_SELF, PATH_INFO, SCRIPT_NAME,와 REQUEST_URI? 당신의 도움을 주셔서 감사합니다!

참고 : 나는 밑줄이 보이기 때문에 공백을 추가해야했으며 어떤 이유로 든 기울임 꼴로 만듭니다.

업데이트 됨 : 공백을 수정했습니다.


PHP 문서는 당신에게 그 차이를 알 수 있습니다 :

'PHP_SELF'

문서 루트를 기준으로 현재 실행중인 스크립트의 파일 이름입니다. 예를 들어, $ _SERVER [ 'PHP_SELF'] 주소에서 스크립트 http://example.com/test.php/foo.bar는/test.php/foo.bar . __FILE__의 상수는 현재의 전체 경로와 파일 이름을 포함 파일 (예 포함). PHP가 명령 줄 프로세서로 실행되는 경우이 변수에는 PHP 4.3.0 이후의 스크립트 이름이 포함됩니다. 이전에는 사용할 수 없었습니다.

'SCRIPT_NAME'

현재 스크립트의 경로를 포함합니다. 이것은 자신을 가리켜 야하는 페이지에 유용합니다. __FILE__의 상수는 현재의 전체 경로와 파일 이름을 포함 파일 (예 포함).

'REQUEST_URI'

이 페이지에 액세스하기 위해 제공된 URI. 예를 들어, '/index.html' .

PATH_INFO가 문서화되지 않은 것 같습니다 ...


이러한 변수 간의 차이점에 대한 몇 가지 실제 예 :
예 1. PHP_SELF는 요청 된 URL이 http://example.com/test.php/foo/bar 형식 일 때만 SCRIPT_NAME과 다릅니다
.

[PHP_SELF] => /test.php/foo/bar
[SCRIPT_NAME] => /test.php

(이것은 PATH_INFO에 합리적인 정보가 포함 된 유일한 경우 인 것 같습니다. [PATH_INFO] => / foo / bar) 참고 : 일부 이전 PHP 버전 (<= 5.0?)에서는 달라졌습니다.

예 2. 비어 있지 않은 쿼리 문자열을 입력 할 때 REQUEST_URI는 SCRIPT_NAME과 다릅니다.
http://example.com/test.php?foo=bar

[SCRIPT_NAME] => /test.php
[REQUEST_URI] => /test.php?foo=bar

예 3. REQUEST_URI는 서버 측 리디렉션이 적용될 때 SCRIPT_NAME과 다릅니다 (예 : 아파치의 mod_rewrite).

http://example.com/test.php

[REQUEST_URI] => /test.php
[SCRIPT_NAME] => /test2.php

예 4. REQUEST_URI는 스크립트로 HTTP 오류를 처리 할 때 SCRIPT_NAME과 다릅니다.
Apache 지시문 사용 ErrorDocument 404 /404error.php
http://example.com/test.php

[REQUEST_URI] => /test.php
[SCRIPT_NAME] => /404error.php

사용자 지정 오류 페이지 http://example.com/test.php를 사용하는 IIS 서버에서

[SCRIPT_NAME] => /404error.php
[REQUEST_URI] => /404error.php?404;http://example.com/test.php

PATH_INFO 다음과 같이 htaccess를 사용할 때만 사용할 수 있습니다.

예 1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(favicon\.ico|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

동일하게 유지

[SCRIPT_NAME] => /index.php

뿌리

http://domain.com/

[PHP_SELF]     => /index.php
[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)
[REQUEST_URI]  => /
[QUERY_STRING] => 

통로

http://domain.com/test

[PHP_SELF]     => /index.php/test
[PATH_INFO]    => /test
[REQUEST_URI]  => /test
[QUERY_STRING] => 

쿼리 문자열

http://domain.com/test?123

[PHP_SELF]     => /index.php/test
[PATH_INFO]    => /test
[REQUEST_URI]  => /test?123
[QUERY_STRING] => 123

예 2

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(favicon\.ico|robots\.txt)
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

동일하게 유지

[SCRIPT_NAME]  => /index.php
[PHP_SELF]     => /index.php
[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)

뿌리

http://domain.com/

[REQUEST_URI]  => /
[QUERY_STRING] => 

통로

http://domain.com/test

[REQUEST_URI]  => /test
[QUERY_STRING] => url=test

쿼리 문자열

http://domain.com/test?123

[REQUEST_URI]  => /test?123
[QUERY_STRING] => url=test&123

예제 3

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(favicon\.ico|robots\.txt)
RewriteRule ^(([a-z]{2})|(([a-z]{2})/)?(.*))$ index.php/$5 [NC,L,E=LANGUAGE:$2$4]

또는

RewriteRule ^([a-z]{2})(/(.*))?$ $3 [NC,L,E=LANGUAGE:$1]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(favicon\.ico|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

동일하게 유지

[SCRIPT_NAME] => /index.php

뿌리

http://domain.com/

[PHP_SELF]          => /index.php
[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)
[REQUEST_URI]       => /
[QUERY_STRING]      => 
[REDIRECT_LANGUAGE] IS NOT AVAILABLE

통로

http://domain.com/test

[PHP_SELF]          => /index.php/test
[PATH_INFO]         => /test
[REQUEST_URI]       => /test
[QUERY_STRING]      => 
[REDIRECT_LANGUAGE] => 

언어

http://domain.com/en

[PHP_SELF]          => /index.php/
[PATH_INFO]         => /
[REQUEST_URI]       => /en
[QUERY_STRING]      => 
[REDIRECT_LANGUAGE] => en

언어 경로

http://domain.com/en/test

[PHP_SELF]          => /index.php/test
[PATH_INFO]         => /test
[REQUEST_URI]       => /en/test
[REDIRECT_LANGUAGE] => en

Language Query string

http://domain.com/en/test?123

[PHP_SELF]          => /index.php/test
[PATH_INFO]         => /test
[REQUEST_URI]       => /en/test?123
[QUERY_STRING]      => 123
[REDIRECT_LANGUAGE] => en

PHP Paths

    $_SERVER['REQUEST_URI']    = Web path, requested URI
    $_SERVER['PHP_SELF']    = Web path, requested file + path info
    $_SERVER['SCRIPT_NAME']    = Web path, requested file
    $_SERVER['SCRIPT_FILENAME']   = File path, requested file
    __FILE__    = File path, current file

Where

  • File path is a system file path like /var/www/index.php, after alias resolution
  • Web path is a server document path like /index.php from http://foo.com/index.php, and may not even match any file
  • Current file means the included script file, not any script that includes it
  • Requested file means the includer script file, not the included one
  • URI is the HTTP request like /index.php?foo=bar, before any URL rewriting
  • Path info is any extra Apache data located after the script name but before the query string

Order of Operation

  1. Client sends server an HTTP request REQUEST_URI
  2. Server performs any URL rewriting from .htaccess files, etc. to get PHP_SELF
  3. Server separates PHP_SELF into SCRIPT_FILENAME + PATH_INFO
  4. Server performs alias resolution and converts the entire url path to a system file path to get SCRIPT_FILENAME
  5. Resulting script file may include others, where __FILE__ refers to the path to the current file

You may want to look into the URI Class and make use of $this->uri->uri_string()

Returns a string with the complete URI.

For example, if this is your full URL:

http://example.com/index.php/news/local/345

The function would return this:

/news/local/345

Or you could make use of the segments to drill down specific areas without having to come up with parsing/regex values


Personally I use the $REQUEST_URI as it references the URI entered and not the location on the server's disc.


There is very little to add to Odin's answer. I just felt to provide a complete example from the HTTP request to the actual file on the file system to illustrate the effects of URL rewriting and aliases. On the file system the script /var/www/test/php/script.php is

<?php
include ("script_included.php")
?>

where /var/www/test/php/script_included.php is

<?php
echo "REQUEST_URI: " .  $_SERVER['REQUEST_URI'] . "<br>"; 
echo "PHP_SELF: " .  $_SERVER['PHP_SELF'] . "<br>";
echo "QUERY_STRING: " .  $_SERVER['QUERY_STRING'] . "<br>";
echo "SCRIPT_NAME: " .  $_SERVER['SCRIPT_NAME'] . "<br>";
echo "PATH_INFO: " .  $_SERVER['PATH_INFO'] . "<br>";
echo "SCRIPT_FILENAME: " . $_SERVER['SCRIPT_FILENAME'] . "<br>";
echo "__FILE__ : " . __FILE__ . "<br>";  
?>

and /var/www/test/.htaccess is

RewriteEngine On
RewriteRule before_rewrite/script.php/path/(.*) after_rewrite/script.php/path/$1 

and the Apache configuration file includes the alias

Alias /test/after_rewrite/ /var/www/test/php/

and the http request is

www.example.com/test/before_rewrite/script.php/path/info?q=helloword

The output will be

REQUEST_URI: /test/before_rewrite/script.php/path/info?q=helloword
PHP_SELF: /test/after_rewrite/script.php/path/info
QUERY_STRING: q=helloword
SCRIPT_NAME: /test/after_rewrite/script.php
PATH_INFO: /path/info
SCRIPT_FILENAME: /var/www/test/php/script.php
__FILE__ : /var/www/test/php/script_included.php

The following always holds

PHP_SELF = SCRIPT_NAME + PATH_INFO = full url path between domain and query string. 

If there is no mod_rewrite, mod_dir, ErrorDocument rewrite or any form of URL rewriting, we also have

REQUEST_URI = PHP_SELF + ? + QUERY_STRING 

The aliases affect the system file paths SCRIPT_FILENAME and __FILE__, not the URL paths, which are defined before - see exceptions below. Aliases might use the entire URL path, including PATH_INFO. There could be no connection at all between SCRIPT_NAME and SCRIPT_FILENAME .

It is not totally exact that aliases are not resolved at the time the URL path [PHP_SELF] = [SCRIPT_NAME] + [PATH_INFO] is defined, because aliases are considered to search the file system and we know from example 4 in Odin's answer that the file system is searched to determine if the file exists, but this is only relevant when the file is not found. Similarly, mod_dir calls mod_alias to search the file system, but this is only relevant if you have an alias such as Alias \index.php \var\www\index.php and the request uri is a directory.


If you ever forget which variables do what, you can write a little script that uses phpinfo() and call it from a URL with a query string. Since server software installations present the variables that PHP returns it's always a good idea to check the machine's output in case rewrites at the server config file are causing different results than expected. Save it as something like _inf0.php:

<?php
    $my_ip = '0.0.0.0';

   if($_SERVER['REMOTE_ADDR']==$my_ip){
     phpinfo();
   } else {
     //something
   }

Then you would call /_inf0.php?q=500


Backup a second, you've taken the wrong approach to begin with. Why not just do this

RewriteEngine on
RewriteCond $1 !^(images|inc|favicon\.ico|index\.php|robots\.txt)
RewriteRule ^(.*)$ /index.php?url=$1 [L]

instead? Then grab it with $_GET['url'];

참고URL : https://stackoverflow.com/questions/279966/php-self-vs-path-info-vs-script-name-vs-request-uri

반응형