需要有关 PHP“包含”的帮助- 如何将我的网站的路径保存在变量中?
我使用以下方案来包含 PHP 文件:
require($_SERVER['DOCUMENT_ROOT'] . "Path/To/My/Website/Path/To/My/File.php");
我想保存
$_SERVER['DOCUMENT_ROOT'] . 'Path/To/My/Website'
在某个变量中,例如 $my_website
,并写入:
require("$my_website/Path/To/My/File.php");
这样,如果我决定更改网站的路径,我将需要仅在我的代码中的一处修改它。
某些 PHP 文件可能会被包含多次并且来自不同的目录级别。例如:
$_SERVER['DOCUMENT_ROOT']
Path
To
My
Website
Dir1
a.php
Dir2
b.php that includes a.php
Dir3
Dir4
c.php that includes a.php
但是,我不知道该怎么做。
请建议。
I use the following scheme to include PHP files:
require($_SERVER['DOCUMENT_ROOT'] . "Path/To/My/Website/Path/To/My/File.php");
I would like to save
$_SERVER['DOCUMENT_ROOT'] . 'Path/To/My/Website'
in some variable, say $my_website
, and write:
require("$my_website/Path/To/My/File.php");
This way, if I decide to change the path to my website, I will need to modify it only in one place in my code.
Some PHP files may be included several times and from different directory levels. For example:
$_SERVER['DOCUMENT_ROOT']
Path
To
My
Website
Dir1
a.php
Dir2
b.php that includes a.php
Dir3
Dir4
c.php that includes a.php
However, I can't think how to do this.
Please suggest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 包含路径 - 会让你的生活更简单(您甚至可以从 .htaccess 控制它)。
Use include path - will make your life simpler (you can control it even from .htaccess).
我可以想到两种方法来执行此操作:
$my_website
需要“Path/To/My/File.php”;
)I can think of two ways of doing this:
$my_website
require "Path/To/My/File.php";
)我在
config.php
文件中设置了 BASE_PATH 和 BASE_URI 常量,该文件与脚本位于同一文件夹中,并包含在每个脚本中 (require('config.php')):
然后你可以使用:
另一个提示 - 如果你有单独的开发和实时站点,你可以将这些定义放在一个开关中:
I set constants for BASE_PATH and BASE_URI in my
config.php
file, which is in the same folder as the scripts and gets included in each script (require('config.php')
):Then you can use:
One further hint - if you have seperate development and live sites, you can put these definitions in a switch: