PHP中的绝对(或相对?)路径 [英] Absolute (or relative?) path in PHP
问题描述
很抱歉,因为它之前可能会被多次回答,但我的问题有点不同
Sorry for asking it as it may be answered many times before, but my question is little bit different
我喜欢树
/var/www/path/to/my/app/
-- index.php
-- b.php
-- inc/
-- include.php
(我正在访问公司/ index.php中的include.php,
(I'm accessing inc/include.php from index.php,
include "inc/include.php";
)
但是在include.php中,我需要获得APPLICATION的绝对路径root,而不是DOCUMENT_ROOT
所以结果,我需要能够使用这个命令
but in include.php, I need to get absolute path to APPLICATION root, not DOCUMENT_ROOT so in result, I need to be able to use this command
//inc/include.php
include(APP_ROOT."/b.php");
重复,我不想打电话
include("../b.php");
是否有原生功能,如果可能的话?
is there native function, if possible?
我想通过PHP获取PATH,因为任何开源需要有这个路径检测
为什么?如果我想从ajax / 1 / somethiing.php中包含inc / include.php,那么成功但inc / include.php会尝试包含ajax / b.php而不是b.php
I am wanting to get PATH by PHP as any open source need to have this path detection why? If I would want to include inc/include.php from ajax/1/somethiing.php, it success but inc/include.php then tries to include ajax/b.php instead of b.php
我有这棵树
-- index.php
-- b.php
-- inc/
-- include.php
-- ajax/
-- 1/
-- ajax.php
现在看。从index.php,您将调用inc / include.php
Now look. From index.php, you'll call inc/include.php
include("inc/include.php"); //included file
现在,包含文件搜索
include("../b.php");
它会起作用,但是!如果我从ajax / 1 / ajax.php调用include of inc / include.php,就像这样
It will work, but! If I would call include of inc/include.php from ajax/1/ajax.php, like this
include("../../inc/include.php");
它会起作用,但包含的文件会尝试包含
it will work, but included file will try to include
../b.php
../../b.php的路径是相对于包含inc / include.php
得到它的文件?
instead of ../../b.php as path is relative to file which INCLUDED that inc/include.php Got it ?
推荐答案
是否有原生函数,如果可能的话?
is there native function, if possible?
no。文档根是您可以从PHP获得的唯一内容。 (但请注意,在您的方案中,您只需调用 include(b.php);
,因为脚本仍在index.php的上下文中。)
no. The document root is the only thing you can get from PHP. (Note however that in your scenario, you can simply call include("b.php");
because the script is still in the context of index.php.)
重新更新:
您可以在中央配置中定义全局应用程序根目录文件。假设您的应用根目录中有 config.php
。然后做一个
You can define a global application root in a central configuration file. Say you have config.php
in your app root. Then do a
define("APP_ROOT", dirname(__FILE__));
你仍然必须包含配置文件,你必须使用它的相对路径,例如
you still have to include the config file, and you have to use relative paths for it, e.g.
include ("../../../config.php");
但是一旦你这样做了,你可以相对于脚本中的app root工作:
but once you have done that, you can work relative to the app root inside the script:
include (APP_ROOT."/b.php"); <-- Will always return the correct path
这篇关于PHP中的绝对(或相对?)路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!