6

Web サイトの「ルート」URL とディレクトリに関する概念と用語について、助けが必要です。

Web サイトのルートを特定することは可能ですか、それとも恣意的な考えであり、実際のサーバーのルートしか確立できないのでしょうか?

さまざまな場所にあるさまざまな Web サイトで使用される PHP プラグインを作成しているとしますが、Web サイトのベース ディレクトリが何であるかを判断する必要があります。PHP を使用すると、常に DOCUMENT_ROOT と SERVER_NAME、つまりサーバー (または仮想サーバー) の絶対 URL と絶対ディレクトリ パスを特定できます。しかし、ウェブサイト自体がルート ディレクトリまたはサブ ディレクトリに「インストール」されているかどうかはわかりません。Web サイトがサブディレクトリにある場合は、ユーザーが「サブパス」変数を​​明示的に設定する必要があります。正しい?

4

4 に答える 4

14

質問 1 への回答: はい、Web サイトのルート パスを明示的に設定する変数が必要です。次の行を含む各 Web サイトのルートにある 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

于 2011-09-16T18:42:35.597 に答える
8

$url と $dir は常に同じ場所を指していますか?

はい

<?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
于 2011-09-16T18:34:38.223 に答える
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'];
        }
?>
于 2011-09-17T06:05:20.080 に答える
-1

私はちょうど同じ問題を抱えていました。Web サイト構造のルート ディレクトリからリンクやその他のファイルを参照したいと考えていました。

次のことを試しましたが、思い通りに機能しませんでした:

$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>";
于 2015-05-08T11:29:11.573 に答える