在include中使用$ _SERVER ['DOCUMENT_ROOT']是个好主意吗? [英] Is it a good idea to use $_SERVER['DOCUMENT_ROOT'] in includes?

查看:116
本文介绍了在include中使用$ _SERVER ['DOCUMENT_ROOT']是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,这是个好主意吗?

Is this, for example, a good idea?

require_once($_SERVER['DOCUMENT_ROOT'].'/include.php');

如果同一台服务器上有两个虚拟主机,一个虚拟主机,一个虚拟主机,并且使用不同的Apache DocumentRoots,则可以避免在包含源未知的情况下,不必包含绝对路径,并且可以在任何目录中

If you have two virtual hosts on the same server, one for live and one for development, with different Apache DocumentRoots, this would avoid having to include absolute paths when the source of the include is unknown, and may be in any directory.

(注意:以下部分中的文件路径是相对于Web根目录的.实际上,它们类似于/var/www/app/core/init.php,其中/var/www/app是Web根目录)

(Note: file paths in the following section are relative to the web root. They would in fact be like /var/www/app/core/init.php, where /var/www/app is the web root)

例如:我有一个/core/init.php,它是使用整个网站(/file.php/dir/file.php or /dir/dir/file.php)上各个地方的相对路径来调用的.

For instance: I have an /core/init.php which is called using relative paths from places all over the website (/file.php, /dir/file.php or /dir/dir/file.php).

然后,此init.php在fund目录中包括/core的子目录(如/core/func/userfunctions.php中)的几个功能页.

This init.php then includes several function pages, in the fund directory, a subdir of /core (as in /core/func/userfunctions.php).

因此,在init.php中,我可以使用$_SERVER方法,因为如果使用相对路径并尝试从类似/dir/file.php的页面调用函数,该方法就会中断.

So, in init.php, I can use the $_SERVER method, because it breaks if I use a relative path and try to call functions from a page like /dir/file.php.

我看不到任何问题,但总的来说可能会出问题吗?

I can't see any problem with it, but in general what could go wrong?

推荐答案

我看到了未设置$_SERVER['DOCUMENT_ROOT']或不是您期望的值的情况(即,未在CLI或旧IIS中设置,或在某些情况下无效) CGI设置).

I've seen cases where $_SERVER['DOCUMENT_ROOT'] is not set or is not what you would expect (i.e. not set in CLI or old IIS, or invalid in certain CGI setups).

因此,您可以使用dirname(__FILE__)来获取调用该行的脚本的路径.然后,您可以从那里引用相对路径,例如

For that reason you can use dirname(__FILE__) to obtain the path of the script that line is called in. You can then reference relative paths from there e.g.

include dirname(__FILE__) . '/../../other/file.php';

当文件的目录结构已知且不会更改时,我采用上述方法.

I go with the above method when the directory structure of the files is known and is not subject to change.

如果DOCUMENT_ROOT不可用,则以下是合适的替代:

If DOCUMENT_ROOT is not available, the following is a suitable replacement:

substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME']));

这篇关于在include中使用$ _SERVER ['DOCUMENT_ROOT']是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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