【问题标题】:Getting the actual document root in PHP?在 PHP 中获取实际的文档根目录?
【发布时间】:2026-02-02 14:30:01
【问题描述】:

我不确定这个脚本将在哪里运行,所以它必须能够从任何地方访问这个目录。

我试图通过从目录中获取图像文件名来创建图像列表,过滤它们直到我只有我想要的图像格式,然后使用<img> 标记显示它们。

第一阶段非常顺利。输出 HTML 被证明是一个问题。

虽然我可以使用$_SERVER["DOCUMENT_ROOT"] to work with the directories in PHP, it's problematic to output that value as part of the path in thetag'ssrc` 属性。

这是我当前的代码:

$unkwown_files = scandir($_SERVER['DOCUMENT_ROOT'] . "/path/images");
          foreach($unkwown_files as $file) {
            $exploded_filename = explode(".", $file);
            $file_type = array_pop($exploded_filename);
            $accepted_filetypes = [
              "png",
              "jpg",
              "gif",
              "jpeg"
            ];
            $picture_names = [];
            if (in_array($file_type, $accepted_filetypes)) {
              $picture_names[] = $file;
            }
          }
          foreach($picture_names as $picture) {
            $path_to_image =  $_SERVER['DOCUMENT_ROOT'] . "/nodes/images" . $picture;
            echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
          }

【问题讨论】:

  • 如手册中定义的The document root directory under which the current script is executing, as defined in the server's configuration file.。因此,您可以将其保留为 /path/imagesdefine

标签: php html directory server root


【解决方案1】:

一种稍微不同的方法,从一开始就按扩展名过滤文件。

$dir = $_SERVER['DOCUMENT_ROOT'] . "/path/images/";
/*
    glob() searches for files/paths that match the pattern in braces and returns the results 
    as an array. 

    The '*' is a wildcard character as you would expect.

    The flag 'GLOB_BRACE' expands the string so that it tries to match each
    ( From the manual: GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c' )

*/
$col = glob( $dir . "*.{jpg,png,gif,jpeg}", GLOB_BRACE );

/*
    Iterate through the results, with each one being the filepath to the file found.

    As the glob() function searched for the required types we don't need to check 
    if they are in the allowed types array.

    Because you do not wish to display the fullpath to the image, a relative path is 
    preferred - thus we remove, from the path, the document root.
*/
foreach( $col as $index => $file ){
    $path_to_image = str_replace( $_SERVER['DOCUMENT_ROOT'], '', $file );
    echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}

【讨论】:

  • 效果很好!您能否剖析您的答案,以便我了解发生了什么?
【解决方案2】:

试试这个

foreach($picture_names as $picture) {
    $path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images/" . $picture;
    echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}

【讨论】:

    最近更新 更多