Relative paths and nested includes [duplicate]

2020-02-06 18:07发布

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 ?

3条回答
【Aperson】
2楼-- · 2020-02-06 19:02

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');
查看更多
Melony?
3楼-- · 2020-02-06 19:03

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';
查看更多
欢心
4楼-- · 2020-02-06 19:07

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...
查看更多
登录 后发表回答