开发者

PHP - Best way to use above directory includes

开发者 https://www.devze.com 2023-03-16 03:28 出处:网络
I\'m having some problems with some parts of my website are accessing some files from different roots and the includes end sometimes 开发者_如何转开发like this:

I'm having some problems with some parts of my website are accessing some files from different roots and the includes end sometimes 开发者_如何转开发like this:

require_once ('../eggs/libs/lagger/lagger_config.php');
require_once ('../eggs/libs/lagger/lagger_init.php');

and sometimes like this:

require_once("../libs/lagger/lagger_config.php");
require_once("../libs/lagger/lagger_init.php");

is there a better way to solve this problem, without having to use the:

../../


If you've got a file that gets run for every request (like a front controller) you can do something like this:

define('APP_PATH', realpath(dirname(__FILE__)));

Then, in your individual scripts:

require_once APP_PATH . '/library/whatever.php';


Best way is to get the base directory, i.e.

define("ROOT",$_SERVER["DOCUMENT_ROOT"]);
define("LAGGER",ROOT."/lagger/"):

then:

require_once(LAGGER."lagger_config.php");
require_once(LAGGER."lagger_init.php");

P.s. I suggest this as you can then use ROOT to build up paths that will be consistent.


set_include_path('../eggs/libs/lagger/');

require_once("lagger_config.php");
require_once("lagger_init.php");

The only benefit to this is you can use ../ only once, instead of with every include. However, when the amount of ../ changes, you'll still need to declare the appropriate path.

On the other hand, if your script has access to the root directory, you can define the include path as {root}/eggs/libs/lagger/ (where {root} is the path to the root) and just set it once, without using relative paths.


Relative paths, like you're doing, are the standard way of including files like you are.

If you dislike that, I've a few projects where I define the 'INCLUDES_FOLDER' to the absolute path.

So your includes would become

require_once(INCLUDES_FOLDER."/libs/lagger/lagger_config.php");
require_once(INCLUDES_FOLDER."/libs/lagger/lagger_init.php");


It's either this or set absolute paths.


ini_set('include_path', ini_get('include_path') . ':/path/to/eggs/libs'));

Putting this at the top of the script, before you do any includes, will save you having to do the paths in each include/require call.

Alternatively you can modify the include_path at the php.ini level so it's permanent for all scripts.


Well you can defined some constants you can use throughout your website:

<?php

   define("ABS_PATH", '../');
   define("DBL_ABS_PATH", '../../');

   //used in code:

   require_once (ABS_PATH.'eggs/libs/lagger/lagger_config.php');
   //and:
   require_once(DBL_ABS_PATH."libs/lagger/lagger_init.php");

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消