我有几个子域包含在我的根站点上方的它们自己的目录中,并且在我的根目录中有一个 assets 文件夹.例如:
<预><代码>//资产//论坛//博客/我正在尝试在根目录和子目录中的 php 页面上的 require() 文件,例如,assets/include/form.php 在根目录和 index.php 中都是 required().php 在论坛目录中.然而,在form.php里面,还有一个require,试图获取包含在include目录中的另一个文件.
我似乎无法找到一种方法来在这个 form.php 中需要一个文件,它可以在根目录的 index.php 和论坛目录的 index.php 上工作.
有什么方法可以明确要求从根目录开始的文件吗?
有几种方法可以实现这一点.
form.php
require_once __DIR__ .'/otherfile.php';
如果您使用的是 PHP 5.2 或更低版本,则可以使用 dirname(__FILE__)
而不是 __DIR__
.在此处阅读有关魔术常量的更多信息.
$_SERVER['DOCUMENT_ROOT']
变量这是文档根目录的绝对路径:/var/www/example.org/
或 C:wampwww
在 Windows 上.
文档根目录是您的根级文件所在的文件夹:http://example.org/index.php 将在 $_SERVER['DOCUMENT_ROOT'] 中.'/index.php'
用法:require_once $_SERVER['DOCUMENT_ROOT'] .'/include/otherfile.php';
如果它非常简单,这对您的应用程序来说可能有点矫枉过正.
您还可以设置使用 require()
或 include()
时 PHP 查找文件的目录.查看set_include_path()
这里.
用法:require_once 'otherfile.php';
注意:
我看到一些答案建议使用 require()
中的 URL.我不建议这样做,因为 PHP 文件会在包含之前被解析.这对于输出 HTML 的 HTML 文件或 PHP 脚本没有问题,但如果您在那里只有一个类定义,您将得到一个空白结果.
I have several subdomains contained in their own directory above my root site, and an assets folder in my root directory. For example:
/
/assets/
/forums/
/blog/
I'm trying to require() files on php pages in both the root directory, and the subdirectories, for example, assets/include/form.php is required() in both index.php in the root directory and index.php in the forums directory. However, inside form.php, is another require, trying to get another file contained in the include directory.
I can't seem to find a way to require a file inside this form.php where it will work on both the root directory's index.php and the forum directory's index.php.
Is there any way I can explicitly require a file starting from the root directory?
There are several ways to achieve this.
form.php
require_once __DIR__ . '/otherfile.php';
If you're using PHP 5.2 or older, you can use dirname(__FILE__)
instead of __DIR__
. Read more about magic constants here.
$_SERVER['DOCUMENT_ROOT']
variableThis is the absolute path to your document root: /var/www/example.org/
or C:wampwww
on Windows.
The document root is the folder where your root level files are: http://example.org/index.php would be in $_SERVER['DOCUMENT_ROOT'] . '/index.php'
Usage: require_once $_SERVER['DOCUMENT_ROOT'] . '/include/otherfile.php';
This will probably be a bit overkill for your application if it's very simple.
You can also set the directories where PHP will look for the files when you use require()
or include()
. Check out set_include_path()
here.
Usage: require_once 'otherfile.php';
Note:
I see some answers suggest using the URL inside a require()
. I would not suggest this as the PHP file would be parsed before it's included. This is okay for HTML files or PHP scripts which output HTML, but if you only have a class definition there, you would get a blank result.
这篇关于PHP 需要顶级目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!