Relative paths and nested includes [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-17 20:32:19

问题


I have a file navbar.php which is in folder views/general. It includes a few relative path files ../controllers/file1.php etc..

I can only include the navbar.php file in other files in the same views/general folder. If I try to include it in a file outside that, like views/signup,

the include paths contained in the navbar.php (../controllers/file1.php etc), won't be relevant anymore.

How can i solve that, so navbar.php can be used from anywhere ?


回答1:


I had a similar challenge and created a single file that defines constants for all the relevant paths that I want to be able to call as-needed. I include this file in all my pages (I define the $urlRoot so that this will work in all environments and is moveable do different domains, etc):

File: pathData.php (added MENUDIR for your example):

$baseDir = dirname(__DIR__) . '/';
$rootUrl = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
define('ROOTURL', $rootUrl);
define('BASEDIR', $baseDir);
define('INCLUDES', $baseDir . 'includes/');
define('INCLUDESURL', ROOTURL . 'includes/');
define('JQUERYURL', ROOTURL . 'includes/jquery/');
define('MENUDIR', ROOTURL . 'views/general/');

Then in each file, I include that file with an include that includes the relative directory path. For example:

include("pathData.php");
or
include("../pathData.php");
or
include("../../pathData.php); 
etc.

So in your case you could (depending on where your pathData file is):

include("../pathData.php");
include(MENUDIR . "navbar.php");
etc...



回答2:


If you're using PHP 5.3+:

include __DIR__ . '/relative/path/from/this/file.php';

__DIR__ is a magic constant holding the absolute path of the current file.

If you're using earlier versions of PHP:

include dirname(__FILE__) . '/relative/path/from/this/file.php';



回答3:


You can also generalise everything from the root directory of your website hosting by using the $_SERVER['DOCUMENT_ROOT'] variable which will be the directory where your index.php should be located.

Use as follows:

include($_SERVER['DOCUMENT_ROOT'] . 'path/from/root/website/location/to/file.php');


来源:https://stackoverflow.com/questions/33499451/relative-paths-and-nested-includes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!