finding a file in php that is 4 directories up

2020-02-16 03:23发布

问题:

I cannot locate the file even when using multiple ../ to find the file:

root -> public -> secure -> lock  -> login / "data.php"
                            panel -> data -> list / "list.php"

I want to include data.php with my list.php and tried doing the following to include the data:

include("../../../../lock/login/data.php");
include("../../../lock/login/data.php");
and also
include("../../lock/login/data.php");

However, this doesn't seem to work, but if I place it beside list.php and do the following, it reads the data just fine:

include("data.php");

What am I doing wrong with my code and what is a better way to execute this?

回答1:

Learn to use:

__FILE__; // for your current file path
dirname(__FILE__) or __DIR__; // for your current file parent folder
$_SERVER['DOCUMENT_ROOT']; // for your sites inception folder, your pivotal point

This should get you on your way. Then you can:

include __DIR__.'/../file-REALLY-relative-to-directory-of-edit-file.php';
include $_SERVER['DOCUMENT_ROOT'].'/absolute-path-reliable-for-your-site.php';

NEVER EVER DO RELATIVE INCLUDES LIKE (current directory can change and break your world):

include 'an-unreliable-NOT-REALLY-relative-file.php';

Hope it helps!



回答2:

Use phps include_path feature instead and specify those directories that contain php scripts to be included. Easier and safer.