确定相对于DOCUMENT_ROOT的文件路径

时间:2015-10-07 11:48:28

标签: php symlink

我的符号链接/var/www/sitename/html/lib/指向/var/www/sitename/application/lib/DOCUMENT_ROOT/var/www/sitename/html/

/var/www/sitename/application/lib/testing/relative.php内,我希望找到此文件相对于文档根目录的路径(即/lib/testing/relative.php)。请注意,relative.php包含一个类,不会直接调用。

如果从位于符号链接(例如https://sitename/lib/testing.php)内的文件中调用relative.php,我可以找到相对于文档根目录的路径,但是,我无法从https://sitename/testing.php

如果不对符号链接的路径进行硬编码,如果从不在符号链接中的文件调用,是否可以找到/var/www/sitename/application/lib/testing/relative.php相对于DOCUMENT_ROOT的路径?

下面显示了我的尝试。

/var/www/sitename/lib/testing/relative.php

<?php
class relative {
    public function __construct()
    {
        $__FILE__=__FILE__;
        $PHP_SELF=$_SERVER['PHP_SELF'];
        $DOCUMENT_ROOT=$_SERVER['DOCUMENT_ROOT'];
        $SCRIPT_FILENAME=$_SERVER['SCRIPT_FILENAME'];
        $SCRIPT_FILENAME_REAL=realpath($_SERVER['SCRIPT_FILENAME']);

        $replace1=str_replace($PHP_SELF,'',$SCRIPT_FILENAME_REAL);
        $replace2=str_replace($replace1,'',__FILE__);

        echo("__FILE__              => $__FILE__\n");
        echo("PHP_SELF              => $PHP_SELF\n");
        echo("DOCUMENT_ROOT         => $DOCUMENT_ROOT\n");
        echo("SCRIPT_FILENAME       => $SCRIPT_FILENAME\n");
        echo("SCRIPT_FILENAME_REAL  => $SCRIPT_FILENAME_REAL\n\n");
        echo('str_replace($PHP_SELF,"",$SCRIPT_FILENAME_REAL)'."\n");
        echo('$replace1             => '.$replace1."\n\n");
        echo('str_replace(str_replace($PHP_SELF,"",$SCRIPT_FILENAME_REAL),"",__FILE__)'."\n");
        echo('$replace2             => '.$replace2);

    }
}
?>

/var/www/sitename/lib/testing.php

<?php
require_once('testing/relative.php');
new relative();  
?>

输出

__FILE__              => /var/www/sitename/application/lib/testing/relative.php
PHP_SELF              => /lib/testing.php
DOCUMENT_ROOT         => /var/www/sitename/html
SCRIPT_FILENAME       => /var/www/sitename/html/lib/testing.php
SCRIPT_FILENAME_REAL  => /var/www/sitename/application/lib/testing.php

str_replace($PHP_SELF,"",$SCRIPT_FILENAME_REAL)
$replace1             => /var/www/sitename/application

str_replace(str_replace($PHP_SELF,"",$SCRIPT_FILENAME_REAL),"",__FILE__)
$replace2             => /lib/testing/relative.php

/var/www/sitename/testing.php

<?php
require_once('lib/testing/relative.php');
new relative();  
?>

输出

__FILE__              => /var/www/sitename/application/lib/testing/relative.php
PHP_SELF              => /testing.php
DOCUMENT_ROOT         => /var/www/sitename/html
SCRIPT_FILENAME       => /var/www/sitename/html/testing.php
SCRIPT_FILENAME_REAL  => /var/www/sitename/html/testing.php

str_replace($PHP_SELF,"",$SCRIPT_FILENAME_REAL)
$replace1             => /var/www/sitename/html

str_replace(str_replace($PHP_SELF,"",$SCRIPT_FILENAME_REAL),"",__FILE__)
$replace2             => /var/www/sitename/application/lib/testing/relative.php

0 个答案:

没有答案