PHP需要顶级文件 [英] PHP require file from top directory

查看:146
本文介绍了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/

我试图在根目录和子目录的php页面上require()例如,assets / include / form.php是根目录中的index.php和forums目录中的index.php的required()。但是,在form.php里面,是另一个需要,试图获得include目录中包含的另一个文件。

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.

我似乎找不到一种方式来要求一个文件在这个form.php里面,它将在根目录的index.php和论坛目录的index.php上工作。

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 in which you can achieve this.


  1. 使用表单中的相对路径.php

    require_once __DIR__。 '/otherfile.php';


    如果您使用PHP 5.2或更早版本,您可以使用 dirname(__ FILE __)而不是 __ DIR __
    http://php.net/manual/en/language.constants.predefined.php

$ _ SERVER [ 'DOCUMENT_ROOT']

使用 $ _ SERVER ['DOCUMENT_ROOT'] 变量。这是您的文档根目录的绝对路径: /var/www/example.org / C:\wamp\www\ 在Windows上。


文档根是根级别文件的文件夹: http://example.org/index.php 将在$ _SERVER ['DOCUMENT_ROOT']中。 '/index.php'

用法: require_once $ _SERVER ['DOCUMENT_ROOT']。 '/include/otherfile.php';

$_SERVER['DOCUMENT_ROOT']
Use the $_SERVER['DOCUMENT_ROOT'] variable. This is the absolute path to your document root: /var/www/example.org/ or C:\wamp\www\ 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';

使用自动加载器

如果非常简单,这可能会对您的应用程序有点过分。

Use an autoloader
This will probably be a bit overkill for your application if it is very simple.

设置PHP的包含路径

您还可以设置PHP在使用require或include时查找文件的目录。

http://php.net/manual/en/function.set-include-path.php

用法: require_once'otherfile.php';

注意:

我看到一些答案建议使用require中的URL。我不会建议,因为PHP文件将被包含在被解析之前。对于输出HTML的HTML文件或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 is included. This is okay for HTML-files or PHP-scripts which outputs HTML, but if you only have a class definition there, you would get a blank result.

这篇关于PHP需要顶级文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆