[英]Absolute (or relative?) path in PHP
很抱歉,因为它可能会被多次回答,但我的问题有点不同
我喜欢树
/var/www/path/to/my/app/
-- index.php
-- b.php
-- inc/
-- include.php
(我正在从index.php访问inc / include.php,
include "inc/include.php";
)
但是在include.php中,我需要获取APPLICATION根的绝对路径,而不是DOCUMENT_ROOT所以在结果中,我需要能够使用这个命令
//inc/include.php
include(APP_ROOT."/b.php");
重复,我不想打电话给他
include("../b.php");
如果可能的话,有原生功能吗?
我想通过PHP获取PATH,因为任何开源需要有这个路径检测的原因? 如果我想要从ajax / 1 / somethiing.php中包含inc / include.php,那么成功但inc / include.php会尝试包含ajax / b.php而不是b.php
我有这棵树
-- index.php
-- b.php
-- inc/
-- include.php
-- ajax/
-- 1/
-- ajax.php
现在看。 从index.php开始,您将调用inc / include.php
include("inc/include.php"); //included file
现在,包含文件搜索
include("../b.php");
它会起作用,但是! 如果我从ajax / 1 / ajax.php调用include of inc / include.php,就像这样
include("../../inc/include.php");
它会工作,但包含文件将尝试包括
../b.php
代替../../b.php作为路径是相对于包含inc / include.php的文件得到了吗?
如果可能的话,有原生功能吗?
没有。 文档根是您可以从PHP获得的唯一内容。 (但请注意,在您的方案中,您只需调用include("b.php");
因为脚本仍在index.php的上下文中。)
重新更新:
您可以在中央配置文件中定义全局应用程序根目录。 假设您的app根目录中有config.php
。 然后做一个
define("APP_ROOT", dirname(__FILE__));
您仍然必须包含配置文件,并且必须使用它的相对路径,例如
include ("../../../config.php");
但是一旦你这样做了,你可以相对于脚本中的app root工作:
include (APP_ROOT."/b.php"); <-- Will always return the correct path
您可以使用当前文件作为基础来解析路径
include dirname(__FILE__) . DIRECTORY_SEPARATOR . '/../b.php';
或者从PHP5.3开始
include __DIR__ . \DIRECTORY_SEPERATOR . '/../b.php';
添加到index.php:
$GLOBALS['YOUR_CODE_ROOT'] = dirname(__FILE__);
添加到您的inc/include.php
:
require_once $GLOBALS['YOUR_CODE_ROOT'].'/b.php';
只是用
define('APP_ROOT', 'your app root');
例如,在index.php中。 或者在配置文件中。
虽然它没有为您定义应用程序的根路径,但可能有必要查看set_include_path()
如果您只知道相对路径,那么您必须至少从相对路径开始。 您可以使用realpath返回规范化的绝对路径名,然后将其存储在某处。
在index.php
或配置文件中:
define(
'INC',
realpath(dirname(__FILE__)) .
DIRECTORY_SEPARATOR .
'inc' .
DIRECTORY_SEPARATOR
);
别处:
include(INC . 'include.php');
或者,为不同的位置定义一些常量:
define('DOCUMENT_ROOT', realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR);
define('INC', DOCUMENT_ROOT . 'inc' . DIRECTORY_SEPARATOR);
define('AJAX', DOCUMENT_ROOT . 'ajax' . DIRECTORY_SEPARATOR);
别处:
include(DOCUMENT_ROOT . 'b.php');
include(INC . 'include.php');
include(AJAX . 'ajax.php');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.