繁体   English   中英

定义 webroot 外部文件夹路径

[英]Define webroot outside folder path

我有这样的文件夹结构:

  public_html
     /index.php   
  outside
     /other.php

我想要public_html/index.php包含文件,它位于outside文件夹中。 所以,我想在public_html/index.php文件中定义外部文件夹路径。 我这样做:

索引.php

 $doc_root_upper = preg_replace("#/[^/]+$#", "", $_SERVER["DOCUMENT_ROOT"]);
 $outside_folder = $doc_root_upper."/outside";
 include outside_folder.'/other.php';

这有效,但是在文件夹路径之外定义 webroot 有更好的做法吗?

我个人的偏好是使用chdir($_SERVER['DOCUMENT_ROOT'])启动我的init.php文件(包含在 php.ini 的auto_prepend_file指令中chdir($_SERVER['DOCUMENT_ROOT'])

这意味着我的所有包含和其他文件功能都是从文档根目录完成的。

在您的情况下,这意味着您可以可靠地include ../outside/other.php

使用这样的相对路径:

Include("../outside/other.php");

../ 表示向上一级目录。

我喜欢使用chdir()来获取显式路径,然后将它们添加到包含路径中。 我倾向于有一个名为init.php的文件,其中包含以下内容:

$path = get_include_path(); // get the current path
$oldcwd = getcwd(); // get the current path

// change to outside of the document root
chdir($_SERVER['DOCUMENT_ROOT'] . "/.."); 
$newcwd = getcwd(); // get the new working directory

// build the new path. Using hte _SEPARATOR constants ensures 
// that it works on all platforms.
$newpath = $path . PATH_SEPARATOR . $newcwd . DIRECTORY_SEPARATOR . "outside"; 

// Set the new path
set_include_path($newpath);

chdir($oldcwd); // change back to the original working directory

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM