确定网站的“根”位置

时间:2011-09-16 18:33:04

标签: php path document-root base-url

我需要一些关于网站“root”网址和目录的概念和术语的帮助。

是否可以确定网站的根目录,或者这是一个随意的想法,只能建立实际服务器的根目录?

假设我正在编写一个PHP插件,该插件将被不同位置的不同网站使用,但需要确定网站的基本目录是什么。使用PHP,我将始终能够确定DOCUMENT_ROOT和SERVER_NAME,即服务器(或虚拟服务器)的绝对URL和绝对目录路径。但我不知道网站本身是“安装”在根目录还是子目录中。如果网站在子目录中,我需要用户明确设置“子路径”变量。正确的吗?

4 个答案:

答案 0 :(得分:13)

回答问题1:是的,您需要一个明确设置网站根路径的变量。可以使用包含以下行的每个网站根目录下的htaccess文件来完成:

SetEnv APP_ROOT_PATH /path/to/app

http://httpd.apache.org/docs/2.0/mod/mod_env.html

您可以使用以下命令在PHP脚本中的任何位置访问它:

<?php $appRootPath = getenv('APP_ROOT_PATH'); ?>

http://php.net/manual/en/function.getenv.php

答案 1 :(得分:6)

  

$ url和$ dir是否总是指向同一个地方?

Yes

<?php 
$some_relative_path = "hello"; 
$server_url = $_SERVER["SERVER_NAME"]; 
$doc_root = $_SERVER["DOCUMENT_ROOT"]; 


echo $url = $server_url.'/'. $some_relative_path."<br />"; 
echo $dir = $doc_root.'/'. $some_relative_path;

输出:

sandbox.phpcode.eu/hello
/data/sandbox//hello

答案 2 :(得分:0)

您无需要求用户提供任何信息。

此代码段将让您的代码知道它是否在根目录中运行:

<?php
        // Load the absolute server path to the directory the script is running in
        $fileDir = dirname(__FILE__);

        // Make sure we end with a slash
        if (substr($fileDir, -1) != '/') {
            $fileDir .= '/';
        }

        // Load the absolute server path to the document root
        $docRoot = $_SERVER['DOCUMENT_ROOT'];

        // Make sure we end with a slash
        if (substr($docRoot, -1) != '/') {
            $docRoot .= '/';
        }

        // Remove docRoot string from fileDir string as subPath string
        $subPath = preg_replace('~' . $docRoot . '~i', '', $fileDir);

        // Add a slash to the beginning of subPath string
        $subPath = '/' . $subPath;          

        // Test subPath string to determine if we are in the web root or not
        if ($subPath == '/') {
            // if subPath = single slash, docRoot and fileDir strings were the same
            echo "We are running in the web foot folder of http://" . $_SERVER['SERVER_NAME'];
        } else {
            // Anyting else means the file is running in a subdirectory
            echo "We are running in the '" . $subPath . "' subdirectory of http://" . $_SERVER['SERVER_NAME'];
        }
?>

答案 3 :(得分:-1)

我刚遇到同样的问题。我想从我网站结构的根目录中引用链接和其他文件。

我尝试了以下内容,但它永远不会按我的意愿行事:

$root = $_SERVER['DOCUMENT_ROOT'];
echo "<a href="' . $root . '/index.php">Link</a>";
echo "<a href="' . $root . '/admin/index.php">Link</a>";

但显而易见的解决办法就是使用以下内容:

echo "<a href="../index.php">Link</a>";
echo "<a href="../admin/index.php">Link</a>";
相关问题