Need help with PHP "include" - How to save the path to my website in variable?
I use the following scheme to include PHP files:
require($_SERVER['DOCUMENT_ROOT'] . "Path/To/My/Website/Path/To/My/File.php");
I would like to save
$_SERVER['DOCUMENT_ROOT'] . 'Path/To/My/Website'
in some variable, say $my_website
, and write:
require("$my_website/Path/To/My/File.php");
This way, if I decide to change the path to my website, I will need to modif开发者_高级运维y it only in one place in my code.
Some PHP files may be included several times and from different directory levels. For example:
$_SERVER['DOCUMENT_ROOT']
Path
To
My
Website
Dir1
a.php
Dir2
b.php that includes a.php
Dir3
Dir4
c.php that includes a.php
However, I can't think how to do this.
Please suggest.
Use include path - will make your life simpler (you can control it even from .htaccess).
I can think of two ways of doing this:
- Create a common file, included in every other file, that set your variable
$my_website
- Add your website path to your include_path so you don't have to use you website path at all to include your files (
require "Path/To/My/File.php";
)
I set constants for BASE_PATH and BASE_URI in my config.php
file, which is in the same folder as the scripts and gets included in each script (require('config.php')
):
define('BASE_PATH', '/filesystem/path/to/application');
define('BASE_URI', '/uri/home');
Then you can use:
require(BASE_PATH . '/file.php');
One further hint - if you have seperate development and live sites, you can put these definitions in a switch:
$mode = 'dev';
switch($mode){
case 'dev':
define('BASE_PATH', '/filesystem/path/to/application');
define('BASE_URI', '/uri/home');
break;
case 'live':
define('BASE_PATH', '/different/path/to/application');
define('BASE_URI', '/');
break;
}
精彩评论