PHP_SELF,SCRIPT_NAME,SCRIPT_FILENAME,PATH_INFO,REQUEST_URI的区别

前言

PHP$_SERVER数组中存在五个和路径相关的变量:PHP_SELFSCRIPT_NAME
SCRIPT_FILENAMEPATH_INFOREQUEST_URI,这五个变量经常会被混淆,做下区分。

测试环境

Nginx0.8.54 + FastCGI + PHP5.3.4

要先配置Nginx的PATH_INFO,在nginx.conf中加入如下配置:

location ~ .* .php {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;

    #从$fastcgi_script_name中分离出真正执行的脚本名称和PATH_INFO
    set $real_script_name $fastcgi_script_name;

    if ($fastcgi_script_name ~ "^(.+?.php)(/.+)$") {
        set $real_script_name $1;
        set $path_info $2;
     }

    #重新设置SCRIPT_FILENAME
    fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
    fastcgi_param  QUERY_STRING       $query_string;
    fastcgi_param  REQUEST_METHOD     $request_method;
    fastcgi_param  CONTENT_TYPE       $content_type;
    fastcgi_param  CONTENT_LENGTH     $content_length;

    #重新设置SCRIPT_NAME

    fastcgi_param SCRIPT_NAME $real_script_name;
    fastcgi_param PATH_INFO $path_info;
    fastcgi_param  REQUEST_URI        $request_uri;
    fastcgi_param  DOCUMENT_URI       $document_uri;
    fastcgi_param  DOCUMENT_ROOT      $document_root;
    fastcgi_param  SERVER_PROTOCOL    $server_protocol;
    fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
    fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;
    fastcgi_param  REMOTE_ADDR        $remote_addr;
    fastcgi_param  REMOTE_PORT        $remote_port;
    fastcgi_param  SERVER_ADDR        $server_addr;
    fastcgi_param  SERVER_PORT        $server_port;
    fastcgi_param  SERVER_NAME        $server_name;

    # PHP only, required if PHP was built with --enable-force-cgi-redirect
    fastcgi_param  REDIRECT_STATUS    200;
}

我们的根目录为/var/www,测试域名为example.com(不过这个域名只能改hosts文件YY一下了),结构如下:

var
 |---www
       |---test
             |---test.php

测试脚本

使用如下脚本进行测试:

<?php
    echo 'SCRIPT_NAME=' . $_SERVER['SCRIPT_NAME'] . '<br />';
    echo 'SCRIPT_FILENAME=' . $_SERVER['SCRIPT_FILENAME'] . '<br />';
    echo 'PATH_INFO=' . $_SERVER['PATH_INFO'] . '<br />';
    echo 'REQUEST_URI=' . $_SERVER['REQUEST_URI'] . '<br />';
?>

测试结果

区别

参考

http://tools.ietf.org/html/draft-robinson-www-interface-00
http://stackoverflow.com/questions/279966/php-self-vs-path-info-vs-script-name-vs-request-uri
http://ca.php.net/manual/en/reserved.variables.server.php

(全文完)
comments powered by Disqus
Powered by Github  &&  Jekyll
Fork me on GitHub